Skip to content

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

Let a group member's approval and slow turn stop blocking the group

Fei24118a4a078a7285
diff --git a/ds-bot/index.js b/ds-bot/index.js
index 4379acdd..22eeb515 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -16,6 +16,7 @@ import * as timeContext from './src/host/time-context.js'
import * as tools from './src/host/tools.js'
import * as chatIndex from './src/host/chat-index.js'
import * as groups from './src/host/groups.js'
+import * as approvals from './src/host/approvals.js'
import * as memory from './src/host/memory.js'
import * as parts from './src/host/parts.js'
import * as images from './src/host/images.js'
@@ -37,7 +38,7 @@ 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, approvals, memory, parts, images, secrets, connectors, schedules, browser, usage, update, dshUpdate, channel]
export function apply(ctx, config = {}) {
const home = config.home ?? join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'bot')
diff --git a/ds-bot/src/host/approvals.js b/ds-bot/src/host/approvals.js
new file mode 100644
index 00000000..9816c2ff
--- /dev/null
+++ b/ds-bot/src/host/approvals.js
@@ -0,0 +1,56 @@
+// Approvals. A member's group Session is hidden, so DSH's approval card never shows
+// there and the turn would wait forever: DS Bot answers those requests itself, from
+// the group chat. A Bot's own chat keeps DSH's card; its requests are only noted, so
+// the team view can say who is waiting.
+import { randomUUID } from 'node:crypto'
+
+const OUTCOMES = { allow: 'allowed-once', reject: 'rejected' }
+
+export function install(rt) {
+ const { ctx } = rt
+ /** @type {Map<string, {id:string, sessionId:string, botId:string, roomId?:string, tool:string, reason:string, detail:{text?:string, code?:string}, at:number, answer?:(outcome:string)=>void}>} */
+ const pending = new Map()
+
+ // Ahead of DSH's own answerer, which would hold a hidden Session's request unseen.
+ ctx.on('approval/request', (request, next) => {
+ const sessionId = request.agent?.session?.id ?? request.agent?.id
+ const owner = sessionId === undefined ? undefined : rt.groupOwners.get(sessionId)
+ const botId = owner?.botId ?? (sessionId === undefined ? undefined : rt.chatOwners.get(sessionId))
+ if (botId === undefined) return next()
+ const id = randomUUID()
+ const entry = {
+ id,
+ sessionId,
+ botId,
+ ...(owner ? { roomId: owner.roomId } : {}),
+ tool: String(request.toolName ?? ''),
+ reason: String(request.reason ?? '').slice(0, 500),
+ detail: rt.callDetail?.(sessionId, request.callId) ?? {},
+ at: Date.now(),
+ }
+ pending.set(id, entry)
+ if (owner === undefined) return Promise.resolve(next()).finally(() => pending.delete(id))
+ rt.yieldRoomTurn?.(sessionId)
+ return new Promise((resolve) => {
+ entry.answer = (outcome) => {
+ if (!pending.delete(id)) return
+ resolve(outcome)
+ }
+ if (request.signal?.aborted) entry.answer('cancelled')
+ request.signal?.addEventListener('abort', () => entry.answer('cancelled'), { once: true })
+ })
+ }, { prepend: true })
+
+ const approvalsView = () => [...pending.values()].map(({ answer, ...entry }) => ({ ...entry, answerable: answer !== undefined }))
+ const waitsForApproval = sessionId => [...pending.values()].some(entry => entry.sessionId === sessionId)
+
+ function answerApproval(id, choice) {
+ const entry = pending.get(String(id ?? ''))
+ if (entry?.answer === undefined) throw Object.assign(new Error('This approval is no longer open'), { code: 'bot/stale' })
+ const outcome = OUTCOMES[choice]
+ if (outcome === undefined) throw Object.assign(new Error('Choose allow or reject'), { code: 'bot/invalid' })
+ entry.answer(outcome)
+ }
+
+ Object.assign(rt, { approvalsView, waitsForApproval, answerApproval })
+}
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 60f59690..96088866 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -67,8 +67,14 @@ 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() })
+ // running; `work`: per Bot, the turn it runs and its tool, and the approvals waiting.
+ const live = () => ({
+ activity: rt.activityView(),
+ work: { bots: rt.workView(), approvals: rt.approvalsView() },
+ memoryNews: rt.memoryNews(),
+ memoryReviews: rt.memoryReviews(),
+ connectors: rt.connectorsView(),
+ })
// 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'])
@@ -196,6 +202,9 @@ export function install(rt) {
await rt.load()
await rt.deleteRoom(body.id)
return ok(view())
+ case 'approval-answer':
+ rt.answerApproval(body.id, body.choice)
+ return ok(true)
case 'dismiss-question':
await rt.load()
if (state.questions[body.sessionId] !== undefined) {
diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.js
index 27ce08bd..fb839370 100644
--- a/ds-bot/src/host/groups.js
+++ b/ds-bot/src/host/groups.js
@@ -12,7 +12,7 @@
import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { defineTool } from '@deepseek-ai/dsh-tools'
-import { ROOM_REPLY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'
+import { ROOM_BOT_ROUNDS, ROOM_REPLY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'
import { escapeRegExp, splitRef, textOf } from './text.js'
import { GROUP_REF, output } from './tools.js'
import { failureLine } from './turns.js'
@@ -103,6 +103,7 @@ const slotLabel = (slot) => {
if (slot.status === 'posted') return `${slot.name} (posted)`
if (slot.status === 'passed') return `${slot.name} (passed)`
if (slot.status === 'missed') return `${slot.name} (no answer)`
+ if (slot.status === 'waiting-approval') return `${slot.name} (waiting for the user's approval; posts when done)`
if (slot.status === 'failed') return `${slot.name} (could not answer: error)`
if (slot.status === 'left') return `${slot.name} (left the group)`
return slot.name
@@ -176,32 +177,45 @@ export function install(rt) {
}
// One member turn inside the room; resolves to its final text, `{ failure }` when its
- // model call failed, or null when it did not answer in time or the round was stopped.
+ // model call failed, `{ missed }` when it went quiet for too long, `{ approval }` when
+ // it waits for the user's approval, or null when the round was stopped. The wait
+ // restarts on each event of the member's Session, so a member at work is never cut off.
async function roomTurn(room, member, sessionId, text, note, signal) {
if (signal.aborted) return null
const exchangeId = randomUUID()
room.seen[member.id] = room.seq
const done = new Promise((resolve) => {
+ let timer
const finish = (value) => {
clearTimeout(timer)
rt.roomWaiters.delete(exchangeId)
resolve(value)
}
- const timer = setTimeout(() => finish(null), ROOM_REPLY_TIMEOUT_MS)
- rt.roomWaiters.set(exchangeId, { resolve: finish, fail: failure => finish({ failure }) })
+ const touch = () => {
+ clearTimeout(timer)
+ timer = setTimeout(() => finish({ missed: true }), ROOM_REPLY_TIMEOUT_MS)
+ }
+ touch()
+ rt.roomWaiters.set(exchangeId, { sessionId, resolve: finish, fail: failure => finish({ failure }), touch, approval: () => finish({ approval: true }) })
signal.addEventListener('abort', () => finish(null), { once: true })
})
try {
await rt.deliver({ fromId: undefined, toId: member.id, sessionId, role: 'room', roomId: room.id, exchangeId, note, text })
+ // Still held by an earlier request: this turn cannot start until the user answers.
+ if (rt.waitsForApproval?.(sessionId)) rt.roomWaiters.get(exchangeId)?.approval()
} catch (error) {
rt.warn('ds-bot: group delivery to %s failed: %s', member.name, error)
rt.roomWaiters.get(exchangeId)?.resolve(null)
}
const reply = await done
- if (reply === null || reply?.failure !== undefined) return reply
+ if (reply === null || typeof reply === 'object') return reply
return stripOwnName(member.name, String(reply ?? '').trim())
}
+ const waitersOf = sessionId => [...rt.roomWaiters.values()].filter(waiter => waiter.sessionId === sessionId)
+ rt.touchRoomTurn = (sessionId) => { for (const waiter of waitersOf(sessionId)) waiter.touch() }
+ rt.yieldRoomTurn = (sessionId) => { for (const waiter of waitersOf(sessionId)) waiter.approval() }
+
// A called member moves up if it is still waiting, or gets one more turn if it
// already spoke; either way it goes right after slot `index`. `cap` is the caller's
// per-member turn bound for the round.
@@ -302,9 +316,16 @@ export function install(rt) {
round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })
continue
}
- if (reply === null || isPass(reply)) {
- slot.status = reply === null ? 'missed' : 'passed'
+ // The member's turn goes on in the background and posts when it ends.
+ if (reply?.approval) {
+ slot.status = 'waiting-approval'
+ round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })
+ continue
+ }
+ if (reply === null || reply?.missed || isPass(reply)) {
+ slot.status = typeof reply === 'string' ? 'passed' : 'missed'
round.passed.push(member.name)
+ if (reply?.missed) round.replies.push({ kind: 'missed', botId: member.id, name: member.name, color: member.color, time: Date.now() })
continue
}
slot.status = 'posted'
@@ -457,12 +478,43 @@ export function install(rt) {
const members = room.members.map(rt.botOf).filter(bot => bot && bot.id !== opener.botId)
const admin = members.find(bot => rt.isAdminOf(room, bot.id))
if (opener.kickoff) return admin ? [admin] : []
+ if (opener.quiet) return []
const { all, found } = mentionsIn(withoutReferences(opener.text, opener.references), members)
+ if (opener.late) return found.length > 0 ? found : admin ? [admin] : []
if (found.length > 0 && !all) return found
if (!all && room.mode === 'admin' && admin) return [admin]
return admin ? [admin, ...members.filter(bot => bot !== admin)] : members
}
+ // A Bot's message into the group's own Session, which relays it as a new round.
+ async function postToRoom(room, sender, text, extra = {}) {
+ const agent = await rt.resolveAgent(room.id)
+ agent.followup(createUserMessage({
+ content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }],
+ source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, hop: 0, ...extra },
+ }))
+ await ctx.sessions.flush(agent.session)
+ }
+ rt.postToRoom = postToRoom
+
+ // A member the round moved on from (it went quiet or waited for an approval) posts
+ // what its turn ended with. Only the admin and anyone it names answer, and past the
+ // Bot round limit nobody does, so late posts cannot keep a group talking.
+ async function lateRoomReply(sessionId, info, reply) {
+ const owner = rt.groupOwners.get(sessionId)
+ const room = rt.roomOf(owner?.roomId ?? info.roomId)
+ const member = rt.botOf(owner?.botId)
+ if (room === undefined || member === undefined || !room.members.includes(member.id)) return
+ const text = stripOwnName(member.name, reply)
+ if (isPass(text)) return
+ const quiet = (room.botRounds ?? 0) >= ROOM_BOT_ROUNDS
+ if (!quiet) room.botRounds = (room.botRounds ?? 0) + 1
+ await rt.save()
+ await postToRoom(room, member, text, { late: true, ...(quiet ? { quiet: true } : {}) })
+ .catch(error => rt.warn('ds-bot: late group reply from %s failed: %s', member.name, error))
+ }
+ rt.lateRoomReply = lateRoomReply
+
// A group the user just made opens with its admin asking what the group is for.
async function greetRoom(roomId) {
const room = rt.roomOf(roomId)
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index ade3c930..f1eb5e89 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -1,9 +1,8 @@
// Team tools: the roster, bot-to-bot messages, group chat settings and posts, and the
// question card. Group rounds and reading chats are in groups.js.
import { randomUUID } from 'node:crypto'
-import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { defineTool } from '@deepseek-ai/dsh-tools'
-import { COLORS, EXTRA_COLORS, MAX_HOPS, ROOM_BOT_ROUNDS, ROOM_MODES, SOURCE_KIND } from './constants.js'
+import { COLORS, EXTRA_COLORS, MAX_HOPS, ROOM_BOT_ROUNDS, ROOM_MODES } from './constants.js'
import { unquote } from './text.js'
export const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] }
@@ -357,22 +356,7 @@ export function install(rt) {
await rt.save()
const reportBack = args.report_back === true
try {
- const agent = await rt.resolveAgent(room.id)
- agent.followup(createUserMessage({
- content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }],
- source: {
- kind: SOURCE_KIND,
- form: 'relay',
- role: 'post',
- exchangeId: randomUUID(),
- senderName: sender.name,
- senderSessionId: sender.id,
- roomId: room.id,
- hop: info?.hop ?? 0,
- ...(reportBack ? { reportBack: true } : {}),
- },
- }))
- await ctx.sessions.flush(agent.session)
+ await rt.postToRoom(room, sender, text, { hop: info?.hop ?? 0, ...(reportBack ? { reportBack: true } : {}) })
} catch (failure) {
return `Could not post in "${room.name}": ${failure.message}`
}
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index 95bc26e3..eab4a82d 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -36,7 +36,7 @@ export function install(rt) {
/** @type {Map<string, {turn?:number, pending?:any, info?:any, texts:string[], opened?:boolean, joined?:{info:any, from:number}[]}>} */
const live = new Map()
- /** @type {Map<string, {resolve:(text:string)=>void}>} member turn waiters keyed by exchange id */
+ /** @type {Map<string, {sessionId:string, resolve:(text:string|null)=>void, fail:(failure:any)=>void, touch:()=>void, approval:()=>void}>} member turn waiters keyed by exchange id */
const roomWaiters = new Map()
/** @type {Map<string, {roomId:string, replies:any[], members:string[], speaking:string|null}>} */
const roomProgress = new Map()
@@ -119,9 +119,34 @@ export function install(rt) {
if (job.roomId === undefined) merged[job.botId] = 'thinking'
else merged[job.botId] ??= 'thinking'
}
+ for (const approval of rt.approvalsView?.() ?? []) merged[approval.botId] = 'alert'
return merged
}
+ // Per Bot, the turn it is running and its current tool; its own chat wins over a group.
+ const workView = () => {
+ const bots = {}
+ for (const [id, entry] of live) {
+ if (entry.turn === undefined) continue
+ const owner = rt.groupOwners.get(id)
+ const botId = owner?.botId ?? rt.chatOwners.get(id)
+ if (botId === undefined || (owner !== undefined && bots[botId] !== undefined)) continue
+ bots[botId] = { since: entry.since, ...(entry.tool ? { tool: entry.tool } : {}), ...(owner ? { roomId: owner.roomId } : {}) }
+ }
+ return bots
+ }
+
+ // What a running tool call is about, for an approval card: its own description and
+ // the command, path or address it acts on.
+ const callDetail = (sessionId, callId) => {
+ let args
+ try { args = JSON.parse(live.get(sessionId)?.calls?.get(callId) ?? '{}') } catch { args = {} }
+ const first = keys => keys.map(key => args?.[key]).find(value => typeof value === 'string' && value.trim() !== '')
+ const text = first(['description', 'justification'])
+ const code = first(['command', 'cmd', 'file_path', 'path', 'url', 'query'])
+ return { ...(text ? { text: text.trim().slice(0, 300) } : {}), ...(code ? { code: code.trim().slice(0, 400) } : {}) }
+ }
+
// Where a Session speaks, for the diagnostics log.
const placeOf = (id) => {
const room = rt.roomOf(rt.groupOwners.get(id)?.roomId) ?? rt.roomOf(id)
@@ -145,16 +170,24 @@ export function install(rt) {
if (id === undefined) return
if (!rt.isBotSession(id) && !rt.roomOf(id)) return
const entry = liveOf(id)
+ if (rt.groupOwners.has(id)) rt.touchRoomTurn?.(id)
switch (event.type) {
- case 'tool/call':
- setActivity(id, event.data?.name === 'ask_user' ? undefined : activityOf(String(event.data?.name ?? '')))
+ case 'tool/call': {
+ const name = String(event.data?.name ?? '')
+ setActivity(id, name === 'ask_user' ? undefined : activityOf(name))
+ entry.tool = name
+ if (typeof event.data?.callId === 'string') (entry.calls ??= new Map()).set(event.data.callId, String(event.data.arguments ?? ''))
break
+ }
case 'tool/result':
if (entry.turn !== undefined) setActivity(id, 'thinking')
+ entry.tool = undefined
+ entry.calls?.delete(event.data?.callId)
break
case 'turn/start':
setActivity(id, 'thinking')
entry.turn = event.data.turn
+ entry.since = event.time ?? Date.now()
entry.texts = []
entry.info = undefined
// A turn turned away before its first step may end without a turn/end.
@@ -198,6 +231,8 @@ export function install(rt) {
name: source.senderName,
reportBack: source.reportBack === true,
hop: source.hop ?? 0,
+ ...(source.late ? { late: true } : {}),
+ ...(source.quiet ? { quiet: true } : {}),
})
} else if (source?.kind === SOURCE_KIND && source.role === 'kickoff' && rt.roomOf(id)) {
queueRoomMessage(id, { text: '', kickoff: true })
@@ -254,6 +289,9 @@ export function install(rt) {
entry.texts = []
entry.switched = false
entry.joined = []
+ entry.since = undefined
+ entry.tool = undefined
+ entry.calls = undefined
const reason = event.data?.reason
const failure = reason?.kind === 'error' && !switched ? turnFailure(reason.error) : undefined
if (failure !== undefined) noteTurnFailure(id, failure)
@@ -290,7 +328,9 @@ export function install(rt) {
const waiter = roomWaiters.get(info.exchangeId)
roomWaiters.delete(info.exchangeId)
if (failure !== undefined) waiter?.fail(failure)
- else waiter?.resolve(reason?.kind === 'aborted' ? null : texts.join('\n\n').trim())
+ else if (waiter !== undefined) waiter.resolve(reason?.kind === 'aborted' ? null : texts.join('\n\n').trim())
+ // The round moved on without this member; what it says now still reaches the group.
+ else if (reason?.kind !== 'aborted') void rt.lateRoomReply?.(id, info, texts.join('\n\n').trim())
} else if (info !== undefined) {
answer(info, texts.join('\n\n').trim())
}
@@ -317,5 +357,5 @@ export function install(rt) {
}
})
- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView })
+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, callDetail })
}
diff --git a/ds-bot/test/group-status.test.js b/ds-bot/test/group-status.test.js
new file mode 100644
index 00000000..fa8bf01c
--- /dev/null
+++ b/ds-bot/test/group-status.test.js
@@ -0,0 +1,151 @@
+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'
+import { ROOM_REPLY_TIMEOUT_MS } from '../src/host/constants.js'
+
+// Chief in its own chat 'a'; Writer, the admin of group 'r1', speaks there from 'gb'.
+const seed = () => ({
+ version: 1,
+ mainBotIds: ['a'],
+ 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: 'b', named: true, sessions: { b: 'gb' }, log: [], seq: 0, seen: {} } },
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+})
+
+async function start() {
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-status-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(seed()))
+ const ctx = fakeContext()
+ const agents = new Map()
+ const agentOf = (sessionId) => {
+ if (!agents.has(sessionId)) {
+ const calls = []
+ agents.set(sessionId, { session: { id: sessionId }, calls, followup(message) { calls.push(message) }, steer(message) { calls.push(message) } })
+ }
+ return agents.get(sessionId)
+ }
+ Object.assign(ctx, {
+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },
+ sessionController: { create: async () => ({ sessionId: 's1' }), resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }), selectModel: async () => {} },
+ 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 })
+ let seq = 0
+ const emit = (id, type, data) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data })
+ }
+ }
+ const tool = (name, args, sessionId, exec = {}) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId }, ...exec })
+ const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))).json()
+ const askApproval = (sessionId, extra = {}, next = () => 'from-dsh') => ctx.listeners.get('approval/request')[0]({ agent: { session: { id: sessionId } }, toolName: 'pwsh', reason: 'escalate sandbox', ...extra }, next)
+ const stop = () => { ctx.dispose(); rmSync(home, { recursive: true, force: true }) }
+ await tool('list_bots', {}, 'a')
+ return { agentOf, emit, tool, call, askApproval, stop }
+}
+
+// Waits on real I/O (state writes) without timers, which some tests mock.
+const settle = async (check) => {
+ const until = Date.now() + 3000
+ while (!check() && Date.now() < until) await new Promise(resolve => setImmediate(resolve))
+ assert.ok(check(), 'condition not reached')
+}
+const text = message => message.content.map(block => block.text ?? '').join('\n')
+
+// Starts a round in 'r1' and opens Writer's turn in 'gb'; the round stops with the test.
+async function openTurn(t, { agentOf, emit, tool }) {
+ let result
+ const stop = new AbortController()
+ t.after(() => stop.abort())
+ void tool('group_relay', {}, 'r1', { callId: 'c1', signal: stop.signal }).then((value) => { result = JSON.parse(value) })
+ await settle(() => agentOf('gb').calls.length === 1)
+ const message = agentOf('gb').calls[0]
+ emit('gb', 'turn/start', { turn: 1 })
+ emit('gb', 'user/message', { content: message.content, source: message.source })
+ return () => result
+}
+
+test('a group Session\'s approval waits in the team view, frees the round, and the late reply reaches the group', async (t) => {
+ const host = await start()
+ t.after(host.stop)
+ const result = await openTurn(t, host)
+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'pwsh', arguments: JSON.stringify({ command: 'Copy-Item a.md E:/docs', description: 'Copy the doc' }) })
+ const outcome = host.askApproval('gb', { callId: 'k1' })
+
+ await settle(() => result() !== undefined)
+ assert.deepEqual(result().replies.map(reply => [reply.kind, reply.name]), [['approval', 'Writer']])
+
+ const { value } = await host.call('state', {})
+ assert.equal(value.activity.b, 'alert')
+ const [approval] = value.work.approvals
+ assert.deepEqual([approval.botId, approval.roomId, approval.tool, approval.answerable], ['b', 'r1', 'pwsh', true])
+ assert.deepEqual(approval.detail, { text: 'Copy the doc', code: 'Copy-Item a.md E:/docs' })
+ assert.equal(value.work.bots.b.roomId, 'r1')
+ assert.equal(value.work.bots.b.tool, 'pwsh')
+
+ assert.equal((await host.call('approval-answer', { id: approval.id, choice: 'allow' })).ok, true)
+ assert.equal(await outcome, 'allowed-once')
+ assert.equal((await host.call('approval-answer', { id: approval.id, choice: 'allow' })).error.code, 'bot/stale')
+ assert.deepEqual((await host.call('state', {})).value.work.approvals, [])
+
+ host.emit('gb', 'tool/result', { callId: 'k1' })
+ host.emit('gb', 'assistant/message', { message: { content: [{ type: 'text', text: 'Writer: Copied the doc to E:/docs.' }] } })
+ host.emit('gb', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ await settle(() => host.agentOf('r1').calls.length === 1)
+ const post = host.agentOf('r1').calls[0]
+ assert.deepEqual([post.source.role, post.source.late, post.source.senderSessionId], ['post', true, 'b'])
+ assert.equal(text(post), '[Group post from Writer]\nCopied the doc to E:/docs.')
+})
+
+test('an own chat\'s approval stays with DSH and is listed while it waits', async (t) => {
+ const host = await start()
+ t.after(host.stop)
+ let release
+ const outcome = host.askApproval('a', {}, () => new Promise((resolve) => { release = resolve }))
+ const [approval] = (await host.call('state', {})).value.work.approvals
+ assert.deepEqual([approval.botId, approval.roomId, approval.answerable], ['a', undefined, false])
+ assert.equal((await host.call('approval-answer', { id: approval.id, choice: 'allow' })).error.code, 'bot/stale')
+ release('rejected')
+ assert.equal(await outcome, 'rejected')
+ assert.deepEqual((await host.call('state', {})).value.work.approvals, [])
+ // Sessions off the team are not DS Bot's to answer.
+ assert.equal(await host.askApproval('elsewhere'), 'from-dsh')
+})
+
+test('a member at work keeps its turn; one quiet for the whole wait is missed, and a later [PASS] stays out of the group', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] })
+ const host = await start()
+ t.after(host.stop)
+ const result = await openTurn(t, host)
+ t.mock.timers.tick(ROOM_REPLY_TIMEOUT_MS - 1000)
+ host.emit('gb', 'tool/call', { callId: 'k1', name: 'shell', arguments: '{}' })
+ t.mock.timers.tick(ROOM_REPLY_TIMEOUT_MS - 1000)
+ await settle(() => true)
+ assert.equal(result(), undefined)
+
+ t.mock.timers.tick(1000)
+ await settle(() => result() !== undefined)
+ assert.deepEqual(result().replies.map(reply => [reply.kind, reply.name]), [['missed', 'Writer']])
+
+ host.emit('gb', 'assistant/message', { message: { content: [{ type: 'text', text: '[PASS]' }] } })
+ host.emit('gb', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ await settle(() => true)
+ assert.equal(host.agentOf('r1').calls.length, 0)
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index f01c8550..67bc4839 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -57,6 +57,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'tool read_own_chat',
'tool read_group_chat',
'on llm/stream',
+ 'on approval/request (prepend)',
'effect ds-bot: memory section',
'prompt bot-memory 645',
'tool remember',