A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Plumb IM needs through store, groups, approvals, turns and channel
Fei24117be1bd610c41
diff --git a/ds-bot/src/host/approvals.js b/ds-bot/src/host/approvals.jsindex 9e7fa71a..76440578 100644--- a/ds-bot/src/host/approvals.js+++ b/ds-bot/src/host/approvals.js@@ -1,7 +1,8 @@// 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.+// the group chat. A Bot's own chat keeps DSH's card, but DS Bot can answer those too+// (IM chats, the phone app): the request is raced — whichever side answers first wins,+// and the other card withdraws.import { randomUUID } from 'node:crypto'const OUTCOMES = { allow: 'allowed-once', reject: 'rejected' }@@ -10,6 +11,16 @@ 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()+ const approvalListeners = new Set()+ const onApproval = (listener) => {+ approvalListeners.add(listener)+ return () => approvalListeners.delete(listener)+ }+ const emit = (kind, data) => {+ for (const listener of approvalListeners) {+ try { listener(kind, data) } catch (error) { rt.warn('ds-bot: approval listener failed: %s', error) }+ }+ }// Ahead of DSH's own answerer, which would hold a hidden Session's request unseen.ctx.on('approval/request', (request, next) => {@@ -30,16 +41,42 @@ export function install(rt) {}pending.set(id, entry)rt.noteApproval?.(sessionId, { tool: entry.tool, reason: entry.reason.slice(0, 200) })- const settled = () => {+ emit('open', { ...entry, answerable: true })+ const settle = (outcome) => {+ if (!pending.has(id)) return falsepending.delete(id)rt.noteApproval?.(sessionId, undefined)+ emit('settled', { id, outcome })+ return true+ }+ if (owner === undefined) {+ // An own-chat approval races DSH's card. The card sees `linked`, our own+ // AbortSignal: answering here resolves the request, then withdraws the card;+ // an answer there settles `next()` first and is adopted. An abort of the+ // original signal cancels either way.+ const original = request.signal+ const linked = new AbortController()+ request.signal = linked.signal+ return new Promise((resolve) => {+ const complete = (outcome) => {+ if (!settle(outcome)) return+ resolve(outcome)+ linked.abort()+ if (request.signal === linked.signal) request.signal = original+ }+ entry.answer = complete+ if (original?.aborted) entry.answer('cancelled')+ else original?.addEventListener('abort', () => entry.answer('cancelled'), { once: true })+ Promise.resolve(next()).then((outcome) => {+ if (!pending.has(id)) return+ complete(outcome)+ })+ })}- if (owner === undefined) return Promise.resolve(next()).finally(settled)rt.yieldRoomTurn?.(sessionId)return new Promise((resolve) => {entry.answer = (outcome) => {- if (!pending.has(id)) return- settled()+ if (!settle(outcome)) returnresolve(outcome)}if (request.signal?.aborted) entry.answer('cancelled')@@ -65,5 +102,5 @@ export function install(rt) {}}- Object.assign(rt, { approvalsView, waitsForApproval, answerApproval, cancelApprovals })+ Object.assign(rt, { approvalsView, waitsForApproval, answerApproval, cancelApprovals, onApproval })}diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 5ce6b836..7eb51e8f 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -83,6 +83,8 @@ export function install(rt) {memory: rt.memoryEnabled !== false,// Set while another dsh host holds the team (store.js): why this one cannot change it.readOnly: rt.readOnly() ?? null,+ // IM connections (settings → IM): one per chat-app bot the user added.+ im: rt.imView?.() ?? { connections: [], platforms: [] },})// What changes without a new revision, sent with every state answer. `learning`:// each Bot's pending skill proposals. `memoryNews`:@@ -98,6 +100,7 @@ export function install(rt) {learning: rt.learningView(),connectors: rt.connectorsView(),capabilityStatuses: rt.capabilityStatusesView(),+ imStatus: rt.imStatusView?.() ?? {},})// The live fields' sources are spread across the host with no single change// counter, so the serialized answer itself is the detector: a poll whose `live`@@ -433,25 +436,7 @@ export function install(rt) {case 'answer-question': {if (typeof body.sessionId !== 'string') return fail('Nothing to send', 'bot/invalid')await rt.load()- const past = rt.pastOwners.get(body.sessionId)- const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId) : past && past.roomId === undefined ? rt.chatOf(past.botId) : body.sessionId- const question = rt.own(state.questions, sessionId)- if (question === undefined || question.id !== body.questionId) return fail('This question is no longer open', 'bot/stale')- const reply = questionReply(question, body.answer)- if (reply === undefined) return fail('Nothing to send', 'bot/invalid')- // Claim the question before queueing so a second answer is refused.- delete state.questions[sessionId]- try {- await rt.ensureCapabilities(sessionId)- const agent = await rt.resolveAgent(sessionId)- agent.followup(createUserMessage({ content: [{ type: 'text', text: reply.text }], source: reply.source }))- await ctx.sessions.flush(agent.session)- } catch (error) {- state.questions[sessionId] ??= question- throw error- }- await rt.save()- return ok(true)+ return ok(await rt.answerQuestion(body.sessionId, body.questionId, body.answer))}case 'view-reply': {if (typeof body.sessionId !== 'string') return fail('Nothing to send', 'bot/invalid')@@ -482,21 +467,7 @@ export function install(rt) {const text = String(body.text ?? '').trim()if (text === '' || typeof body.sessionId !== 'string') return fail('Nothing to send', 'bot/invalid')await rt.load()- // A Bot id, a group chat's id, or an earlier part of either means the- // current part.- const past = rt.pastOwners.get(body.sessionId)- const room = rt.roomOf(body.sessionId)- const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId)- : room !== undefined ? rt.sessionOfRoom(room)- : past?.roomId === undefined && past !== undefined ? rt.chatOf(past.botId)- : past !== undefined ? rt.sessionOfRoom(rt.roomOf(past.roomId)) : body.sessionId- await rt.ensureCapabilities(sessionId)- await ctx.sessionController.prompt({- requestId: randomUUID(),- sessionId,- mode: 'queue',- content: [{ type: 'text', text }],- }, AbortSignal.timeout(30_000))+ await rt.sendUser({ sessionId: body.sessionId, content: [{ type: 'text', text }] })return ok(true)}case 'btw-delete': {@@ -605,6 +576,17 @@ export function install(rt) {rt.browserChannel?.setHold(botId, { by: 'user', reason: 'stopped', note: 'The user is controlling this browser.' })return ok(true)}+ case 'im-add':+ case 'im-update':+ case 'im-remove':+ case 'im-pair':+ case 'im-unpair':+ case 'im-chat':+ case 'im-retry':+ case 'im-login-start':+ case 'im-login-wait':+ await rt.load()+ return ok(await rt.imEndpoint(endpoint, body))case 'diagnostics':await rt.load()return ok(await rt.diagnostics.report(body))@@ -624,6 +606,51 @@ export function install(rt) {}}+ // How a user message reaches a Session: a Bot id, a group chat's id, or an earlier+ // part of either resolves to its current part. `content` is the prompt blocks DSH+ // takes (text, image, file receipts); `requestId` lands on the message's source.+ async function sendUser({ sessionId: ref, content, requestId = randomUUID() }) {+ const past = rt.pastOwners.get(ref)+ const room = rt.roomOf(ref)+ const sessionId = rt.botOf(ref) ? rt.chatOf(ref)+ : room !== undefined ? rt.sessionOfRoom(room)+ : past?.roomId === undefined && past !== undefined ? rt.chatOf(past.botId)+ : past !== undefined ? rt.sessionOfRoom(rt.roomOf(past.roomId)) : ref+ await rt.ensureCapabilities(sessionId)+ await ctx.sessionController.prompt({+ requestId,+ sessionId,+ mode: 'queue',+ content,+ }, AbortSignal.timeout(30_000))+ }++ // The user's answer to an ask_user card, from the web or an IM chat. A Bot id or an+ // earlier part of its own chat means the current one.+ async function answerQuestion(sessionRef, questionId, answer) {+ const past = rt.pastOwners.get(sessionRef)+ const sessionId = rt.botOf(sessionRef) ? rt.chatOf(sessionRef) : past && past.roomId === undefined ? rt.chatOf(past.botId) : sessionRef+ const question = rt.own(state.questions, sessionId)+ if (question === undefined || question.id !== questionId) throw Object.assign(new Error('This question is no longer open'), { code: 'bot/stale' })+ const reply = questionReply(question, answer)+ if (reply === undefined) throw Object.assign(new Error('Nothing to send'), { code: 'bot/invalid' })+ // Claim the question before queueing so a second answer is refused.+ delete state.questions[sessionId]+ try {+ await rt.ensureCapabilities(sessionId)+ const agent = await rt.resolveAgent(sessionId)+ agent.followup(createUserMessage({ content: [{ type: 'text', text: reply.text }], source: reply.source }))+ await ctx.sessions.flush(agent.session)+ } catch (error) {+ state.questions[sessionId] ??= question+ throw error+ }+ await rt.save()+ return true+ }++ Object.assign(rt, { sendUser, answerQuestion })+// An exact Fetch route on the shared /api channel; the browser authenticates with its session cookie.ctx.effect(() => ctx.connection.fetch.register({path: ROUTE,diff --git a/ds-bot/src/host/feed.js b/ds-bot/src/host/feed.jsindex 98719a3f..6ff1e6c5 100644--- a/ds-bot/src/host/feed.js+++ b/ds-bot/src/host/feed.js@@ -32,9 +32,9 @@ export function install(rt) {for (const controller of clients) send(controller, chunk)}- rt.stateSaved = () => {+ const offSaved = rt.onSaved(() => {if (clients.size > 0) publish('revision', { revision: state.revision })- }+ })let liveTimerconst live = () => {@@ -109,6 +109,7 @@ export function install(rt) {return () => {clearInterval(keepalive)clearTimeout(liveTimer)+ offSaved()for (const controller of clients) leave(controller)}}, 'ds-bot: live feed')diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 563fc39e..8430c6bc 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -232,15 +232,25 @@ export function install(rt) {return length > shown.length ? `${shown}… (cut; ${length} characters in all)` : shown}+ const roomLineListeners = new Set()const appendRoom = (room, line) => {room.seq += 1- const log = [...room.log, keepGroupLine(room.id, { ...line, seq: room.seq }, line.text ?? '')]+ const whole = { ...line, seq: room.seq }+ const log = [...room.log, keepGroupLine(room.id, whole, line.text ?? '')]for (const gone of log.slice(0, -ROOM_LOG_MAX)) dropGroupLine(room.id, gone)room.log = log.slice(-ROOM_LOG_MAX)+ // Listeners see the whole line, before keepGroupLine cut it for the log.+ for (const listener of roomLineListeners) {+ try { listener(room, whole) } catch (error) { rt.warn('ds-bot: room line listener failed: %s', error) }+ }}Object.assign(rt, {keepGroupLine, dropGroupLines,logRoom: (room, line) => { ensureRoomLog(room); appendRoom(room, line) },+ onRoomLine: (listener) => {+ roomLineListeners.add(listener)+ return () => roomLineListeners.delete(listener)+ },})// The folder a group was set to work in is gone: its members' Sessions move on indiff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex c72d19fb..66658a44 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -1375,7 +1375,9 @@ export function install(rt) {if (source?.kind === 'user') {const content = Array.isArray(event.data.content) ? event.data.content : []const images = content.filter(block => block?.type === 'image').length- stamp(event, { kind: 'user', text: textOf(content), ...(images > 0 ? { images } : {}), time: event.time })+ // A message that came in over IM carries im:<platform>:<uuid> as its requestId.+ const via = typeof source.rpcId === 'string' && source.rpcId.startsWith('im:') ? source.rpcId.split(':')[1] : undefined+ stamp(event, { kind: 'user', text: textOf(content), ...(images > 0 ? { images } : {}), ...(via ? { via } : {}), time: event.time })} else if (source?.kind === REPLY_KIND) {const text = textOf(event.data.content)const reply = readReply(text)diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex d08b1722..9d8e393e 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -384,7 +384,9 @@ export function install(rt) {await replaceFile(temp, statePath, ensureLock)seen = stamp()rt.capabilitiesStateSaved?.()- rt.stateSaved?.()+ for (const listener of savedListeners) {+ try { listener() } catch (error) { warn('ds-bot: saved listener failed: %s', error) }+ }} catch (error) {await unlink(temp).catch(() => {})throw error@@ -503,8 +505,14 @@ export function install(rt) {}const isAdminOf = (room, id) => id !== undefined && room.admin === id+ const savedListeners = new Set()+ const onSaved = (listener) => {+ savedListeners.add(listener)+ return () => savedListeners.delete(listener)+ }+Object.assign(rt, {- state, load, save, refresh, readOnly, own,+ state, load, save, refresh, readOnly, own, onSaved,botOf, roomOf, isMain, chatOf, sessionOfRoom, selfOf, isBotSession,chatOwners, groupOwners, roomOwners, pastOwners,groupSessionsOf, dropGroupSession, retireGroupSession, findBot, findRooms, isAdminOf,diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 1339f3af..e314506a 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -264,6 +264,23 @@ export function install(rt) {}}+ // The phone's Stop for a Bot's own-chat turn: the same cancel the group's+ // member stop uses — end the running turn and any subagents it spawned.+ async function stopChat(botId) {+ await rt.load()+ const sessionId = rt.chatOf(botId)+ if (sessionId === undefined) return false+ const turnRunning = live.get(sessionId)?.turn !== undefined+ const subRunning = hasSubagents?.(sessionId) === true+ if (!turnRunning && !subRunning) return false+ await stopSubagents(sessionId)+ if (turnRunning) {+ const agent = await rt.resolveAgent(sessionId).catch(() => undefined)+ agent?.cancel?.({ kind: 'user' })+ }+ return true+ }+const liveOf = id => {let entry = live.get(id)if (entry === undefined) live.set(id, entry = { texts: [], shown: 0 })@@ -1122,5 +1139,5 @@ export function install(rt) {}, 'ds-bot: prompt rejection reasons')}- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents })+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, stopChat, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents })}diff --git a/ds-bot/test/group-status.test.js b/ds-bot/test/group-status.test.jsindex c4b46f5d..0b3a3da8 100644--- a/ds-bot/test/group-status.test.js+++ b/ds-bot/test/group-status.test.js@@ -134,16 +134,18 @@ test('a group Session\'s approval waits in the team view, frees the round, and tassert.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) => {+test('an own chat\'s approval races DSH\'s card and is listed while it waits', async (t) => {const host = await start()t.after(host.stop)let releaseconst 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')+ assert.deepEqual([approval.botId, approval.roomId, approval.answerable], ['a', undefined, true])+ assert.equal((await host.call('approval-answer', { id: approval.id, choice: 'allow' })).ok, true)+ assert.equal(await outcome, 'allowed-once')+ // DSH's card answering late is ignored once DS Bot settled the race.release('rejected')- assert.equal(await outcome, 'rejected')+ 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, [])// Sessions off the team are not DS Bot's to answer.assert.equal(await host.askApproval('elsewhere'), 'from-dsh')