Skip to content

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

Add the IM core with the Telegram adapter

Fei2411657478a847da
diff --git a/NOTICE b/NOTICE
index fdfb8072..0395fcf4 100644
--- a/NOTICE
+++ b/NOTICE
@@ -91,6 +91,37 @@ Apache License, Version 2.0, Copyright (c) Microsoft Corporation
The license is the same Apache License, Version 2.0 that covers this
repository; see LICENSE for the text.
+dsh-im (https://github.com/xmanrui/dsh-im)
+MIT License, Copyright (c) 2026 xmanrui
+
+ - ds-bot/src/host/im/platforms/telegram.js follows the Telegram Bot API
+ mapping of dsh-im's telegram channel (long polling, getFile downloads,
+ callback queries, and its send/edit calls), and
+ ds-bot/src/host/im/format.js follows the Markdown chunking of
+ src/channels/shared/markdown-chunks.mjs and telegram-rich-message.mjs
+ there: code fences stay whole where they fit and are re-fenced when
+ they must be split.
+
+ The MIT License text:
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
No other third-party code is copied into this repository. At run time the
plugin uses the @deepseek-ai/* packages of the DeepSeek Harness install it
runs in; they are not bundled. The bundled ds-bot/office.js includes
diff --git a/ds-bot/index.js b/ds-bot/index.js
index a524d360..895df0d6 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -41,6 +41,7 @@ import * as dshUpdate from './src/host/dsh-update.js'
import * as thinking from './src/host/thinking.js'
import * as channel from './src/host/channel.js'
import * as feed from './src/host/feed.js'
+import * as im from './src/host/im/index.js'
import * as officeSkills from './src/host/office-skills.js'
import * as goalSkills from './src/host/goal-skills.js'
@@ -54,7 +55,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
// install. Listeners run and tools are listed in registration order, so this order holds:
// usage meters model requests after every listener that rewrites them. privacy checks a
// call before the hooks of tools do, so a closed call never reaches a card they show.
-const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills, goalSkills]
+const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, im, channel, officeSkills, goalSkills]
export function apply(ctx, config = {}) {
createRuntime(ctx, config)
diff --git a/ds-bot/src/host/im/format.js b/ds-bot/src/host/im/format.js
new file mode 100644
index 00000000..848a1c52
--- /dev/null
+++ b/ds-bot/src/host/im/format.js
@@ -0,0 +1,169 @@
+// Outbound text for IM platforms. Bots write Markdown; each platform adapter turns it
+// into what the platform renders (Telegram HTML) or plain text, and cuts it at the
+// platform's per-message limit without breaking inside a code fence when it can help it.
+
+const escapeHtml = text => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+
+// Inline Markdown inside one line or block: `code`, **bold**, _italic_, ~~strike~~,
+// [label](url). Code spans are pulled out first so markers inside them stay literal.
+function inlineHtml(line) {
+ const spans = []
+ const kept = line.replace(/`([^`]+)`/g, (_all, code) => {
+ spans.push(`<code>${escapeHtml(code)}</code>`)
+ return `\x00${spans.length - 1}\x00`
+ })
+ const html = escapeHtml(kept)
+ .replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (_all, label, url) => `<a href="${escapeHtml(url)}">${label}</a>`)
+ .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
+ .replace(/__([^_]+)__/g, '<b>$1</b>')
+ .replace(/\*([^*]+)\*/g, '<i>$1</i>')
+ .replace(/\b_([^_]+)_\b/g, '<i>$1</i>')
+ .replace(/~~([^~]+)~~/g, '<s>$1</s>')
+ return html.replace(/\x00(\d+)\x00/g, (_all, index) => spans[Number(index)])
+}
+
+function inlinePlain(line) {
+ return line
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (_all, label, url) => (label === url ? label : `${label} (${url})`))
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/__([^_]+)__/g, '$1')
+ .replace(/\*([^*]+)\*/g, '$1')
+ .replace(/\b_([^_]+)_\b/g, '$1')
+ .replace(/~~([^~]+)~~/g, '$1')
+}
+
+// One Markdown document as blocks: fenced code stays a block of its own so chunking
+// can keep it whole; the rest splits on blank lines.
+function blocks(markdown) {
+ const out = []
+ const lines = String(markdown).split('\n')
+ let at = 0
+ let buffer = []
+ const flush = () => {
+ if (buffer.length > 0) out.push({ kind: 'text', lines: buffer })
+ buffer = []
+ }
+ while (at < lines.length) {
+ const line = lines[at]
+ const fence = /^```(\S*)\s*$/.exec(line)
+ if (fence !== null) {
+ flush()
+ const close = lines.slice(at + 1).findIndex(item => /^```\s*$/.test(item))
+ const body = close === -1 ? lines.slice(at + 1) : lines.slice(at + 1, at + 1 + close)
+ out.push({ kind: 'code', lang: fence[1] ?? '', lines: body, open: true })
+ at += 1 + (close === -1 ? body.length : close + 1)
+ continue
+ }
+ if (line.trim() === '') flush()
+ else buffer.push(line)
+ at += 1
+ }
+ flush()
+ return out
+}
+
+const renderHtml = block => (block.kind === 'code'
+ ? `<pre><code${block.lang ? ` class="language-${escapeHtml(block.lang)}"` : ''}>${escapeHtml(block.lines.join('\n'))}</code></pre>`
+ : block.lines.map(inlineHtml).join('\n'))
+
+const renderPlain = block => (block.kind === 'code' ? block.lines.join('\n') : block.lines.map(inlinePlain).join('\n'))
+
+export function toTelegramHtml(markdown) {
+ return blocks(markdown).map(renderHtml).join('\n')
+}
+
+export function toPlain(markdown) {
+ return blocks(markdown).map(renderPlain).join('\n')
+}
+
+const points = text => Array.from(text).length
+
+// Split a block that alone exceeds the limit: text at line boundaries (a line that
+// is still too long is cut where it lands — Telegram answers it as plain text), a
+// code fence into several fenced blocks.
+function forceCut(block, limit) {
+ if (block.kind !== 'code') {
+ const chunks = []
+ let html = ''
+ let text = ''
+ const flush = () => {
+ if (html === '') return
+ chunks.push({ html, text })
+ html = ''
+ text = ''
+ }
+ for (const line of block.lines) {
+ const lineHtml = inlineHtml(line)
+ const candidate = html === '' ? lineHtml : `${html}\n${lineHtml}`
+ if (points(candidate) <= limit) {
+ html = candidate
+ text = text === '' ? inlinePlain(line) : `${text}\n${inlinePlain(line)}`
+ continue
+ }
+ flush()
+ // A single line over the limit is cut on its rendered text.
+ let rest = lineHtml
+ let restPlain = inlinePlain(line)
+ while (points(rest) > limit) {
+ const part = Array.from(rest).slice(0, limit).join('')
+ const plainPart = Array.from(restPlain).slice(0, limit).join('')
+ chunks.push({ html: part, text: plainPart })
+ rest = Array.from(rest).slice(limit).join('')
+ restPlain = Array.from(restPlain).slice(limit).join('')
+ }
+ html = rest
+ text = restPlain
+ }
+ flush()
+ return chunks
+ }
+ const chunks = []
+ const open = `<pre><code${block.lang ? ` class="language-${escapeHtml(block.lang)}"` : ''}>`
+ const close = '</code></pre>'
+ let body = block.lines.join('\n')
+ const room = limit - points(open) - points(close)
+ while (body !== '') {
+ let at = Math.min(points(body), Math.max(1, room))
+ const chars = Array.from(body)
+ const newline = body.lastIndexOf('\n', at)
+ if (newline > room / 2) at = newline
+ const part = chars.slice(0, at).join('')
+ chunks.push({ html: `${open}${escapeHtml(part)}${close}`, text: part })
+ body = chars.slice(at).join('').replace(/^\n/, '')
+ }
+ return chunks
+}
+
+// Chunks of one Markdown message, each under `limit` rendered characters. Block
+// boundaries are kept where possible; a fence is only split when it alone is too big.
+export function chunkTelegram(markdown, limit = 4096) {
+ const chunks = []
+ let html = ''
+ let text = ''
+ const flush = () => {
+ if (html === '' && text === '') return
+ chunks.push({ html, text })
+ html = ''
+ text = ''
+ }
+ for (const block of blocks(markdown)) {
+ const blockHtml = renderHtml(block)
+ const blockText = renderPlain(block)
+ const candidate = html === '' ? blockHtml : `${html}\n${blockHtml}`
+ if (points(candidate) <= limit) {
+ html = candidate
+ text = text === '' ? blockText : `${text}\n${blockText}`
+ continue
+ }
+ flush()
+ if (points(blockHtml) <= limit) {
+ html = blockHtml
+ text = blockText
+ continue
+ }
+ chunks.push(...forceCut(block, limit))
+ }
+ flush()
+ return chunks
+}
diff --git a/ds-bot/src/host/im/index.js b/ds-bot/src/host/im/index.js
new file mode 100644
index 00000000..69d1df58
--- /dev/null
+++ b/ds-bot/src/host/im/index.js
@@ -0,0 +1,839 @@
+// IM: talk to Bots from chat apps. A connection is one IM bot account bound to a Bot;
+// direct chats reach that Bot, platform group chats can be bound to a DS Bot group.
+// The platform adapters (im/platforms/) own the wire; this module owns pairing,
+// routing, cards and the send queues. Only the dsh holding the team lock connects.
+import { randomBytes, randomUUID } from 'node:crypto'
+import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { replaceFile } from '../files.js'
+import { imPlatform, IM_PLATFORMS } from '../../shared/im-platforms.js'
+import { adapters } from './platforms/index.js'
+
+const RECONCILE_MS = 15_000
+const RUNTIME_SAVE_MS = 400
+const RETRY_MS = 5_000
+const TYPING_MS = 4_000
+const NUMBERS = /^\s*\d+(\s+\d+)*\s*$/
+
+const secretField = key => key.replace(/[A-Z]/g, char => `_${char}`).toUpperCase()
+
+export function install(rt) {
+ const { ctx, state } = rt
+ const imDir = join(rt.home, 'im')
+ const zh = () => String(rt.uiLanguage?.() ?? '').startsWith('Chinese')
+ const text = (key, values = {}) => {
+ const line = {
+ requested: zh() ? '已向 DS Bot 发出连接请求,请在电脑上的 DS Bot 设置 → IM 里允许。' : 'A connection request was sent to DS Bot; allow it in Settings → IM on the computer.',
+ unbound: zh() ? '这个 IM 机器人还没绑定 Bot,请在 DS Bot 设置 → IM 里选一个。' : 'This IM bot is not bound to a Bot yet; pick one in DS Bot Settings → IM.',
+ unboundGroup: zh() ? '这个群还没绑定,请在 DS Bot 设置 → IM 里给它选一个群或 Bot。' : 'This group is not bound yet; pick a group or a Bot for it in DS Bot Settings → IM.',
+ connected: zh() ? `已连接,现在可以和 ${values.target} 说话了。` : `Connected — you can talk to ${values.target} now.`,
+ stopped: zh() ? '已停下。' : 'Stopped.',
+ idle: zh() ? '现在没有在做的活。' : 'Nothing is running.',
+ stale: zh() ? '这张卡已经答过了。' : 'This card was already answered.',
+ noFile: zh() ? '这个文件发不过去,请在电脑上发。' : 'This file cannot be sent here; send it on the computer.',
+ greeting: zh() ? `你好,我是 ${values.name}。` : `Hello, I am ${values.name}.`,
+ question: zh() ? `${values.bot} 问你:` : `${values.bot} asks: `,
+ approval: zh() ? `${values.bot} 请你审批:` : `${values.bot} asks for approval: `,
+ secretAsk: zh() ? `${values.bot} 要密钥 ${values.name},请在电脑或手机 App 上填。` : `${values.bot} needs the key ${values.name} — fill it on the computer or the phone app.`,
+ viewShow: zh() ? `${values.bot} 发了一个卡片,请在电脑或手机 App 上回复。` : `${values.bot} shared a card — answer it on the computer or the phone app.`,
+ answered: zh() ? '已答' : 'answered',
+ numbers: zh() ? '回复编号' : 'reply with the number',
+ numbersMulti: zh() ? '回复编号,多选用空格隔开' : 'reply with the numbers, separated by spaces',
+ allow: zh() ? '允许一次' : 'Allow once',
+ reject: zh() ? '拒绝' : 'Reject',
+ }[key]
+ return line ?? key
+ }
+
+ // ---------------------------------------------------------------- runtime file
+ const runtimes = new Map() // id → { data: {runtime, cards, open}, timer }
+ const runtimeOf = async (id) => {
+ let held = runtimes.get(id)
+ if (held !== undefined) return held
+ let data
+ try {
+ data = JSON.parse(await readFile(join(imDir, `${id}.json`), 'utf8'))
+ } catch { data = undefined }
+ held = {
+ data: {
+ runtime: data?.runtime !== null && typeof data?.runtime === 'object' ? data.runtime : {},
+ cards: data?.cards !== null && typeof data?.cards === 'object' ? data.cards : {},
+ },
+ timer: undefined,
+ }
+ runtimes.set(id, held)
+ return held
+ }
+ const scheduleWrite = (id) => {
+ const held = runtimes.get(id)
+ if (held === undefined || held.timer !== undefined) return
+ held.timer = setTimeout(() => {
+ held.timer = undefined
+ void writeRuntime(id).catch(error => rt.warn('ds-bot: im runtime %s not saved: %s', id, error))
+ }, RUNTIME_SAVE_MS)
+ held.timer.unref?.()
+ }
+ const writeRuntime = async (id) => {
+ const held = runtimes.get(id)
+ if (held === undefined || rt.readOnly() !== undefined) return
+ await mkdir(imDir, { recursive: true })
+ const temp = join(imDir, `${id}.${process.pid}.tmp`)
+ try {
+ await writeFile(temp, JSON.stringify(held.data), { encoding: 'utf8', mode: 0o600 })
+ await chmod(temp, 0o600)
+ await replaceFile(temp, join(imDir, `${id}.json`))
+ } catch (error) {
+ await rm(temp, { force: true }).catch(() => {})
+ throw error
+ }
+ }
+ const runtimeEnv = async (id) => {
+ const held = await runtimeOf(id)
+ return {
+ get: () => held.data.runtime,
+ set: (patch) => {
+ Object.assign(held.data.runtime, patch)
+ scheduleWrite(id)
+ },
+ }
+ }
+ // Sent cards: cardKey → [{ chatKey, messageId, answer? }]. Persisted so a restart
+ // does not send a card twice; an `answer` marks it settled from this side.
+ const cardsOf = async (id) => (await runtimeOf(id)).data
+ const markCard = async (id, cardKey, chatKey, messageId, body) => {
+ const data = await cardsOf(id)
+ const entries = data.cards[cardKey] ?? []
+ const held = entries.find(entry => entry.chatKey === chatKey)
+ if (held !== undefined) {
+ held.messageId = messageId ?? held.messageId
+ held.text = body ?? held.text
+ } else {
+ entries.push({ chatKey, messageId, text: body })
+ }
+ data.cards[cardKey] = entries
+ scheduleWrite(id)
+ }
+ const settleCard = async (id, cardKey, answer) => {
+ const data = await cardsOf(id)
+ const entries = data.cards[cardKey]
+ if (entries === undefined) return
+ for (const entry of entries) entry.answer ??= answer
+ scheduleWrite(id)
+ }
+
+ // ------------------------------------------------------------- connections
+ const connections = () => (state.im ??= { connections: {} }).connections
+ const adaptersFor = () => Object.keys(adapters)
+ const hasSecrets = conn => Object.values(conn.secrets ?? {}).every(name => rt.secretValue(name) !== undefined)
+ const fieldsOf = (conn) => {
+ const fields = { ...conn.settings }
+ for (const [key, name] of Object.entries(conn.secrets ?? {})) fields[key] = rt.secretValue(name)
+ return fields
+ }
+ const envFor = async (conn) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: rt.config.im?.[conn.platform],
+ runtime: await runtimeEnv(conn.id),
+ log: { warn: (template, ...args) => rt.warn(template, ...args) },
+ uploadFile: async (sessionId, file) => {
+ const uploads = ctx.get?.('fileUploads')
+ if (typeof uploads?.uploadStream !== 'function') throw new Error('no upload service')
+ const data = file.data?.[Symbol.asyncIterator] !== undefined ? file.data : (async function* () { yield file.data })()
+ const value = await uploads.uploadStream({ sessionId, data, name: file.name })
+ return value.receiptId
+ },
+ })
+
+ // ------------------------------------------------------------------ send out
+ /** @type {Map<string, {handle:any, queues:Map<string, {jobs:any[], retry?:any}>, statuses:Map}>} */
+ const runners = new Map()
+ const statuses = new Map()
+ const setStatus = (id, next) => statuses.set(id, { at: Date.now(), ...next })
+ const targetsOf = (conn) => {
+ const out = []
+ for (const [chatKey, chat] of Object.entries(conn.chats ?? {})) {
+ const target = chat.target ?? (chat.kind === 'direct' ? { botId: conn.botId } : undefined)
+ out.push({ chatKey, chat, target })
+ }
+ return out
+ }
+ // Chats of this connection that listen to a Bot's own chat or a group.
+ const listeners = (conn, match) => targetsOf(conn).filter(({ target }) => {
+ if (match.botId !== undefined) return target?.botId === match.botId && rt.botOf(target.botId) !== undefined
+ if (match.roomId !== undefined) return target?.roomId === match.roomId && rt.roomOf(target.roomId) !== undefined
+ return false
+ })
+
+ const failClass = (error) => {
+ if (error?.permanent === true || (typeof error?.status === 'number' && error.status >= 400 && error.status < 500 && error.status !== 429)) return 'permanent'
+ if (error?.unknown === true || error?.stopped === true) return 'drop'
+ return 'retry'
+ }
+
+ const enqueue = (conn, chatKey, job) => {
+ const runner = runners.get(conn.id)
+ if (runner === undefined) return
+ let queue = runner.queues.get(chatKey)
+ if (queue === undefined) runner.queues.set(chatKey, queue = { jobs: [] })
+ queue.jobs.push(job)
+ if (queue.jobs.length === 1) void drain(conn, chatKey)
+ }
+ const drain = async (conn, chatKey) => {
+ const runner = runners.get(conn.id)
+ const queue = runner?.queues.get(chatKey)
+ if (runner === undefined || queue === undefined) return
+ while (queue.jobs.length > 0) {
+ const job = queue.jobs[0]
+ try {
+ const sent = await runner.handle.send(job.chat, job)
+ job.after?.(sent)
+ queue.jobs.shift()
+ } catch (error) {
+ const how = failClass(error)
+ if (how === 'retry') {
+ const wait = Number(error?.retryAfter) > 0 ? error.retryAfter * 1000 : RETRY_MS
+ queue.retry = setTimeout(() => { void drain(conn, chatKey) }, wait)
+ queue.retry.unref?.()
+ return
+ }
+ queue.jobs.shift()
+ if (how === 'permanent') setStatus(conn.id, { state: 'error', error: String(error?.message ?? error).slice(0, 300) })
+ }
+ }
+ }
+ const sendText = (conn, chat, body, buttons, after) => enqueue(conn, chat.key, { chat, text: body, buttons, after })
+ const sendTo = (conn, chatKey, chat, body, buttons, after) => enqueue(conn, chatKey, { chat, text: body, buttons, after })
+
+ // ----------------------------------------------------------------- inbound
+ const paired = (conn, senderId) => (conn.paired ?? []).some(entry => entry.id === senderId)
+ const requested = (conn, msg) => {
+ if ((conn.requests ?? []).some(entry => entry.id === msg.sender.id)) return false
+ conn.requests = [...(conn.requests ?? []), { id: msg.sender.id, name: msg.sender.name, chatKey: msg.chat.key, chatKind: msg.chat.kind, at: Date.now() }]
+ return true
+ }
+
+ const targetName = (conn, target) => {
+ if (target?.botId !== undefined) return rt.botOf(target.botId)?.name
+ if (target?.roomId !== undefined) return rt.roomOf(target.roomId)?.name
+ return undefined
+ }
+ const resolveTarget = (conn, chat) => {
+ const target = chat.target ?? (chat.kind === 'direct' ? { botId: conn.botId } : undefined)
+ if (target?.botId !== undefined && rt.botOf(target.botId) !== undefined) return target
+ if (target?.roomId !== undefined && rt.roomOf(target.roomId) !== undefined) return target
+ return undefined
+ }
+
+ // The newest open card for this chat, and how to answer it.
+ const openCard = (conn, chatKey, kind) => {
+ const runner = runners.get(conn.id)
+ const data = runtimes.get(conn.id)?.data
+ if (data === undefined) return undefined
+ for (const [cardKey, entries] of Object.entries(data.cards).reverse()) {
+ if (!cardKey.startsWith(`${kind}:`)) continue
+ const entry = entries.find(item => item.chatKey === chatKey && item.answer === undefined)
+ if (entry === undefined) continue
+ return { cardKey, entry }
+ }
+ return undefined
+ }
+ const questionById = (id) => {
+ for (const [sessionId, question] of Object.entries(state.questions ?? {})) {
+ if (question.id === id) return { sessionId, question }
+ }
+ return undefined
+ }
+ const answerQuestionCard = async (conn, chat, labels) => {
+ const held = openCard(conn, chat.key, 'q')
+ if (held === undefined) return false
+ const found = questionById(held.cardKey.slice(2))
+ if (found === undefined) {
+ await sendCardReply(conn, chat, text('stale'))
+ return true
+ }
+ const valid = labels.filter(label => (found.question.options ?? []).some(option => option.label === label))
+ if (valid.length === 0) return false
+ try {
+ await rt.answerQuestion(found.sessionId, found.question.id, { selected: valid })
+ await settleCard(conn.id, held.cardKey, valid.join(', '))
+ await settledEdits(conn)
+ } catch (error) {
+ if (error?.code === 'bot/stale') {
+ await settleCard(conn.id, held.cardKey, text('answered'))
+ await sendCardReply(conn, chat, text('stale'))
+ await settledEdits(conn)
+ return true
+ }
+ throw error
+ }
+ return true
+ }
+ const answerApprovalCard = async (conn, chat, choice) => {
+ const held = openCard(conn, chat.key, 'a')
+ if (held === undefined) return false
+ try {
+ rt.answerApproval(held.cardKey.slice(2), choice)
+ await settleCard(conn.id, held.cardKey, choice === 'allow' ? text('allow') : text('reject'))
+ await settledEdits(conn)
+ } catch (error) {
+ if (error?.code === 'bot/stale') {
+ await sendCardReply(conn, chat, text('stale'))
+ return true
+ }
+ throw error
+ }
+ return true
+ }
+ const sendCardReply = async (conn, chat, body) => sendText(conn, { key: chat.key, kind: chat.kind, title: chat.title }, body)
+
+ const onMessage = (conn) => async (msg) => {
+ if (!paired(conn, msg.sender.id)) {
+ if (msg.chat.kind === 'group' && !msg.mentioned) return
+ if (!requested(conn, msg)) return
+ await rt.save()
+ await sendText(conn, msg.chat, text('requested'))
+ return
+ }
+ conn.chats ??= {}
+ if (msg.chat.kind === 'group' && !msg.mentioned) return
+ if (conn.chats[msg.chat.key] === undefined) {
+ conn.chats[msg.chat.key] = { kind: msg.chat.kind, title: msg.chat.title, at: Date.now() }
+ await rt.save()
+ }
+ const body = String(msg.text ?? '').trim()
+ const chat = conn.chats[msg.chat.key]
+ const target = resolveTarget(conn, chat)
+ if (/^\/start(?:@\S+)?\s*$/.test(body)) {
+ const name = target === undefined ? undefined : targetName(conn, target)
+ await sendText(conn, msg.chat, name === undefined ? text(msg.chat.kind === 'group' ? 'unboundGroup' : 'unbound') : text('greeting', { name }))
+ return
+ }
+ if (/^\/stop(?:@\S+)?\s*$/.test(body)) {
+ if (target === undefined) {
+ await sendText(conn, msg.chat, text(msg.chat.kind === 'group' ? 'unboundGroup' : 'unbound'))
+ return
+ }
+ const stopped = target.botId !== undefined ? await rt.stopChat(target.botId) : await rt.stopRoomWork(target.roomId)
+ await sendText(conn, msg.chat, text(stopped ? 'stopped' : 'idle'))
+ return
+ }
+ if (NUMBERS.test(body)) {
+ const picked = body.trim().split(/\s+/).map(Number)
+ const held = openCard(conn, msg.chat.key, 'q') ?? openCard(conn, msg.chat.key, 'a')
+ if (held !== undefined) {
+ if (held.cardKey.startsWith('q:')) {
+ const found = questionById(held.cardKey.slice(2))
+ if (found !== undefined) {
+ const options = found.question.options ?? []
+ const labels = (found.question.multiSelect === true ? picked : picked.slice(0, 1))
+ .map(index => options[index - 1]?.label)
+ if (labels.every(label => label !== undefined) && labels.length > 0 && await answerQuestionCard(conn, msg.chat, labels)) return
+ if (labels.length > 0 && labels.every(label => label !== undefined)) return
+ if (await answerQuestionCard(conn, msg.chat, [])) return
+ } else if (await sendCardReply(conn, msg.chat, text('stale')).then(() => true)) return
+ } else if (picked.length === 1 && (picked[0] === 1 || picked[0] === 2)) {
+ if (await answerApprovalCard(conn, msg.chat, picked[0] === 1 ? 'allow' : 'reject')) return
+ }
+ }
+ }
+ if (target === undefined) {
+ await sendText(conn, msg.chat, text(msg.chat.kind === 'group' ? 'unboundGroup' : 'unbound'))
+ return
+ }
+ const sessionId = target.botId ?? target.roomId
+ const content = []
+ if (body !== '') content.push({ type: 'text', text: body })
+ for (const image of msg.images ?? []) content.push({ type: 'image', mediaType: image.mediaType, data: image.data })
+ const env = await envFor(conn)
+ for (const file of msg.files ?? []) {
+ try {
+ const receiptId = await env.uploadFile(rt.botOf(sessionId) ? rt.chatOf(sessionId) : sessionId, file)
+ content.push({ type: 'file', receiptId })
+ } catch {
+ await sendText(conn, msg.chat, text('noFile'))
+ }
+ }
+ if (content.length === 0) return
+ await rt.sendUser({ sessionId, content, requestId: `im:${conn.platform}:${randomUUID()}` })
+ }
+
+ const onAction = (conn) => async (action) => {
+ if (!paired(conn, action.sender.id)) return
+ const data = String(action.data ?? '')
+ const chat = { key: action.chat.key, kind: action.chat.kind, title: action.chat.title }
+ if (data.startsWith('q:')) {
+ const [, id, index] = data.split(':')
+ const found = questionById(id)
+ const label = found?.question.options?.[Number(index)]?.label
+ if (label === undefined) {
+ await sendCardReply(conn, chat, text('stale'))
+ return
+ }
+ if (!(await answerQuestionCard(conn, chat, [label]))) await sendCardReply(conn, chat, text('stale'))
+ return
+ }
+ if (data.startsWith('a:')) {
+ const [, , choice] = data.split(':')
+ if (choice === 'allow' || choice === 'reject') {
+ if (!(await answerApprovalCard(conn, chat, choice))) await sendCardReply(conn, chat, text('stale'))
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------ cards
+ const cardText = {
+ question: (bot, question) => {
+ const options = (question.options ?? []).map((option, index) => `${index + 1}. ${option.label}${option.description ? ` — ${option.description}` : ''}`).join('\n')
+ const hint = question.multiSelect === true ? text('numbersMulti') : text('numbers')
+ return `${text('question', { bot })}${question.question}${question.detail ? `\n${question.detail}` : ''}\n${options}\n(${hint})`
+ },
+ approval: (bot, entry) => `${text('approval', { bot })}${entry.tool}${entry.reason ? ` — ${entry.reason}` : ''}${entry.detail?.text ? `\n${entry.detail.text}` : ''}${entry.detail?.code ? `\n${entry.detail.code}` : ''}`,
+ }
+ const cardButtons = {
+ question: (question) => (question.multiSelect === true ? undefined : (question.options ?? []).map((option, index) => ({ data: `q:${question.id}:${index}`, label: option.label }))),
+ approval: (id) => [{ data: `a:${id}:allow`, label: text('allow') }, { data: `a:${id}:reject`, label: text('reject') }],
+ }
+
+ const sendCard = async (conn, cardKey, targets, body, buttons) => {
+ for (const { chatKey, chat } of targets) {
+ sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body, buttons, (sent) => {
+ void markCard(conn.id, cardKey, chatKey, sent?.messageId, body)
+ })
+ }
+ // A card a chat never got (queued behind a failure) is still recorded below.
+ for (const { chatKey } of targets) await markCard(conn.id, cardKey, chatKey, undefined, body)
+ }
+
+ const diffCards = async () => {
+ if (rt.readOnly() !== undefined) return
+ for (const conn of Object.values(connections())) {
+ const runner = runners.get(conn.id)
+ if (runner === undefined) continue
+ const data = await cardsOf(conn.id)
+ // Questions: one card per open question id, sent to the Bot's chats.
+ for (const [sessionId, question] of Object.entries(state.questions ?? {})) {
+ const cardKey = `q:${question.id}`
+ if (data.cards[cardKey] !== undefined) continue
+ const botId = rt.chatOwners.get(sessionId) ?? rt.pastOwners.get(sessionId)?.botId
+ const bot = rt.botOf(botId)
+ if (bot === undefined) continue
+ const buttons = imPlatform(conn.platform)?.buttons === true ? cardButtons.question(question) : undefined
+ await sendCard(conn, cardKey, listeners(conn, { botId }), cardText.question(bot.name, question), buttons)
+ }
+ // Secret requests: text only — the key is typed on the computer or phone.
+ for (const [botId, list] of Object.entries(state.secretRequests ?? {})) {
+ const bot = rt.botOf(botId)
+ if (bot === undefined) continue
+ for (const request of list) {
+ const cardKey = `s:${request.id}`
+ if (request.status !== 'pending' || data.cards[cardKey] !== undefined) continue
+ await sendCard(conn, cardKey, listeners(conn, { botId }), text('secretAsk', { bot: bot.name, name: request.name }))
+ }
+ }
+ // Views awaiting a reply: text form only.
+ for (const [sessionId, view] of Object.entries(state.views ?? {})) {
+ const cardKey = `v:${view.id}`
+ if (data.cards[cardKey] !== undefined) continue
+ const botId = rt.chatOwners.get(sessionId)
+ const bot = rt.botOf(botId)
+ if (bot === undefined) continue
+ await sendCard(conn, cardKey, listeners(conn, { botId }), `${text('viewShow', { bot: bot.name })}${view.title ? `\n${view.title}` : ''}`)
+ }
+ }
+ }
+
+ // Buttons drop and the answer shows wherever the card was settled.
+ const settledEdits = async (conn) => {
+ const runner = runners.get(conn.id)
+ const data = runtimes.get(conn.id)?.data
+ if (runner?.handle.edit === undefined || data === undefined) return
+ for (const [cardKey, entries] of Object.entries(data.cards)) {
+ for (const entry of entries) {
+ if (entry.answer === undefined || entry.messageId === undefined || entry.edited === true) continue
+ const chat = conn.chats?.[entry.chatKey]
+ if (chat === undefined) continue
+ entry.edited = true
+ const body = entry.text !== undefined ? `${entry.text}\n— ${entry.answer}` : `(${text('answered')})`
+ runner.handle.edit({ key: entry.chatKey, kind: chat.kind, title: chat.title }, entry.messageId, { text: body }).catch(() => {})
+ scheduleWrite(conn.id)
+ }
+ }
+ }
+ // A card answered on the computer leaves the state; its IM copy settles too.
+ const settleGone = async () => {
+ for (const conn of Object.values(connections())) {
+ const data = runtimes.get(conn.id)?.data
+ if (data === undefined) continue
+ let touched = false
+ const openIds = new Set(Object.values(state.questions ?? {}).map(question => `q:${question.id}`))
+ const openSecret = new Set(Object.values(state.secretRequests ?? {}).flat().filter(entry => entry.status === 'pending').map(entry => `s:${entry.id}`))
+ const openViews = new Set(Object.values(state.views ?? {}).map(view => `v:${view.id}`))
+ for (const [cardKey, entries] of Object.entries(data.cards)) {
+ const open = cardKey.startsWith('q:') ? openIds.has(cardKey)
+ : cardKey.startsWith('a:') ? rt.approvalsView().some(entry => `a:${entry.id}` === cardKey)
+ : cardKey.startsWith('s:') ? openSecret.has(cardKey)
+ : cardKey.startsWith('v:') ? openViews.has(cardKey) : false
+ if (open) continue
+ for (const entry of entries) {
+ if (entry.answer === undefined) {
+ entry.answer = text('answered')
+ touched = true
+ }
+ }
+ }
+ if (touched) {
+ scheduleWrite(conn.id)
+ await settledEdits(conn)
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------- lifecycle
+ // `state.im.connections` is replaced wholesale when a save is adopted, so anything
+ // bound at connect time looks the connection up again by id instead of keeping it.
+ const fresh = id => connections()[id]
+ const onStatus = (id) => (next) => {
+ setStatus(id, { state: next.state, error: next.error, at: Date.now() })
+ const conn = fresh(id)
+ if (conn !== undefined && next.account !== undefined && (conn.account?.id !== next.account.id || conn.account?.name !== next.account.name)) {
+ conn.account = next.account
+ void rt.save().catch(() => {})
+ }
+ }
+
+ const busyOf = (target) => {
+ if (target?.botId !== undefined) return rt.live.get(rt.chatOf(target.botId))?.turn !== undefined
+ if (target?.roomId !== undefined) return (rt.roomWorkView?.()[target.roomId] ?? []).length > 0
+ return false
+ }
+
+ const start = async (conn) => {
+ const adapter = adapters[conn.platform]
+ if (adapter === undefined) return
+ const platform = imPlatform(conn.platform)
+ if (platform?.ws === true && globalThis.WebSocket === undefined) {
+ setStatus(conn.id, { state: 'error', error: 'This dsh runs on a Node without WebSocket', at: Date.now() })
+ return
+ }
+ setStatus(conn.id, { state: 'connecting', at: Date.now() })
+ const env = await envFor(conn)
+ const runner = { handle: undefined, queues: new Map(), typing: undefined }
+ runners.set(conn.id, runner)
+ try {
+ runner.handle = adapter.connect(fieldsOf(conn), env, {
+ onMessage: (msg) => {
+ const current = fresh(conn.id)
+ return current === undefined ? undefined : onMessage(current)(msg).catch(error => rt.warn('ds-bot: im message failed: %s', error))
+ },
+ onAction: (action) => {
+ const current = fresh(conn.id)
+ return current === undefined ? undefined : onAction(current)(action).catch(error => rt.warn('ds-bot: im action failed: %s', error))
+ },
+ onStatus: onStatus(conn.id),
+ })
+ if (typeof runner.handle?.typing === 'function') {
+ runner.typing = setInterval(() => {
+ for (const { chat, target } of targetsOf(fresh(conn.id) ?? conn)) {
+ if (target !== undefined && busyOf(target)) void runner.handle.typing({ key: chat.key ?? chat, kind: chat.kind, title: chat.title }).catch?.(() => {})
+ }
+ }, TYPING_MS)
+ runner.typing.unref?.()
+ }
+ await diffCards()
+ } catch (error) {
+ runners.delete(conn.id)
+ setStatus(conn.id, { state: 'error', error: String(error?.message ?? error).slice(0, 300), at: Date.now() })
+ }
+ }
+ const stop = async (id) => {
+ const runner = runners.get(id)
+ runners.delete(id)
+ if (runner?.typing !== undefined) clearInterval(runner.typing)
+ for (const queue of runner?.queues.values() ?? []) clearTimeout(queue.retry)
+ await Promise.resolve(runner?.handle?.stop?.()).catch(() => {})
+ if (statuses.get(id)?.state !== 'error') setStatus(id, { state: 'off', at: Date.now() })
+ }
+
+ const sync = async () => {
+ const conns = connections()
+ for (const conn of Object.values(conns)) {
+ const wants = stopped !== true && adapters[conn.platform] !== undefined && conn.enabled !== false
+ && rt.readOnly() === undefined && hasSecrets(conn)
+ if (wants && !runners.has(conn.id)) await start(conn)
+ else if (!wants && runners.has(conn.id)) await stop(conn.id)
+ else if (wants && conn.enabled === false) await stop(conn.id)
+ }
+ for (const id of [...runners.keys()]) if (conns[id] === undefined) await stop(id)
+ for (const id of [...statuses.keys()]) if (conns[id] === undefined) statuses.delete(id)
+ for (const conn of Object.values(conns)) {
+ if (conn.enabled === false || !runners.has(conn.id)) {
+ if (statuses.get(conn.id)?.state !== 'error') setStatus(conn.id, { state: 'off', at: Date.now() })
+ }
+ }
+ }
+
+ let stopped = false
+
+ // ---------------------------------------------------------------- endpoints
+ const secretName = (conn, key) => `IM_${conn.platform.toUpperCase()}_${conn.id.slice(3, 9).toUpperCase()}_${secretField(key)}`
+ const cleanFields = (platform, fields) => {
+ const given = fields !== null && typeof fields === 'object' ? fields : {}
+ const out = {}
+ for (const field of platform.fields) {
+ const value = given[field.key]
+ if (field.options !== undefined) {
+ out[field.key] = field.options.some(([id]) => id === value) ? value : field.options[0][0]
+ } else if (typeof value === 'string' && value.trim() !== '') {
+ out[field.key] = value.trim()
+ } else if (!field.secret) {
+ if (value !== undefined && typeof value !== 'string') throw new Error(`${field.label} must be text`)
+ out[field.key] = ''
+ }
+ // Missing secret fields are allowed only on update, where the saved one stays.
+ }
+ return out
+ }
+
+ const saveSecrets = async (conn, platform, fields) => {
+ for (const field of platform.fields) {
+ if (!field.secret || fields[field.key] === undefined) continue
+ const name = conn.secrets[field.key] ?? secretName(conn, field.key)
+ await rt.secretEndpoint('secret-set', { name, value: fields[field.key], purpose: `${platform.name} IM bot`, scope: [] })
+ conn.secrets[field.key] = name
+ }
+ }
+
+ const viewOf = (conn) => ({
+ id: conn.id,
+ platform: conn.platform,
+ account: conn.account ?? null,
+ botId: conn.botId ?? null,
+ settings: conn.settings ?? {},
+ secrets: Object.keys(conn.secrets ?? {}),
+ enabled: conn.enabled !== false,
+ paired: conn.paired ?? [],
+ requests: conn.requests ?? [],
+ chats: Object.fromEntries(Object.entries(conn.chats ?? {}).map(([key, chat]) => [key, { ...chat }])),
+ createdAt: conn.createdAt,
+ })
+
+ const endpoints = {
+ async 'im-add'(body) {
+ const platform = imPlatform(String(body.platform ?? ''))
+ if (platform === undefined || adapters[platform.id] === undefined) throw new Error('This platform is not available yet')
+ const bot = rt.botOf(String(body.botId ?? ''))
+ if (bot === undefined) throw new Error('Choose a Bot first')
+ if (platform.login === 'qr') throw new Error('This platform signs in by scanning a code; not available yet')
+ const fields = cleanFields(platform, body.fields)
+ for (const field of platform.fields) {
+ if (!field.options && fields[field.key] === undefined) throw new Error(`${field.label} is required`)
+ }
+ const env = await envFor({ id: 'im_check', platform: platform.id, settings: fields, secrets: {} })
+ const { account } = await adapters[platform.id].check(fields, env)
+ const conn = {
+ id: `im_${randomBytes(4).toString('hex')}`,
+ platform: platform.id,
+ account,
+ botId: bot.id,
+ settings: Object.fromEntries(platform.fields.filter(field => !field.secret).map(field => [field.key, fields[field.key]])),
+ secrets: {},
+ enabled: true,
+ paired: [],
+ requests: [],
+ chats: {},
+ createdAt: Date.now(),
+ }
+ await saveSecrets(conn, platform, fields)
+ connections()[conn.id] = conn
+ await rt.save()
+ await sync()
+ return viewOf(conn)
+ },
+ async 'im-update'(body) {
+ const conn = connections()[String(body.id ?? '')]
+ if (conn === undefined) throw new Error('No such IM bot')
+ const platform = imPlatform(conn.platform)
+ if (platform === undefined) throw new Error('No such platform')
+ if (body.botId !== undefined) {
+ const bot = rt.botOf(String(body.botId))
+ if (bot === undefined) throw new Error('Choose a Bot first')
+ conn.botId = bot.id
+ }
+ if (body.enabled !== undefined) conn.enabled = body.enabled === true
+ if (body.fields !== undefined) {
+ const fields = cleanFields(platform, body.fields)
+ const env = await envFor(conn)
+ const check = { ...fields }
+ for (const field of platform.fields) {
+ if (field.secret && check[field.key] === undefined) check[field.key] = rt.secretValue(conn.secrets[field.key])
+ }
+ const { account } = await adapters[conn.platform].check(check, env)
+ conn.account = account
+ await saveSecrets(conn, platform, fields)
+ for (const field of platform.fields) {
+ if (!field.secret && fields[field.key] !== undefined) conn.settings[field.key] = fields[field.key]
+ }
+ }
+ await rt.save()
+ if (runners.has(conn.id)) await stop(conn.id)
+ await sync()
+ return viewOf(conn)
+ },
+ async 'im-remove'(body) {
+ const id = String(body.id ?? '')
+ const conn = connections()[id]
+ if (conn === undefined) throw new Error('No such IM bot')
+ await stop(id)
+ for (const name of Object.values(conn.secrets ?? {})) {
+ await rt.secretEndpoint('secret-delete', { name }).catch(() => {})
+ }
+ delete connections()[id]
+ runtimes.delete(id)
+ await rm(join(imDir, `${id}.json`), { force: true }).catch(() => {})
+ await rt.save()
+ return true
+ },
+ async 'im-pair'(body) {
+ const conn = connections()[String(body.id ?? '')]
+ if (conn === undefined) throw new Error('No such IM bot')
+ const at = (conn.requests ?? []).findIndex(entry => entry.id === String(body.senderId ?? ''))
+ if (at === -1) throw new Error('This request is gone')
+ const [request] = conn.requests.splice(at, 1)
+ if (body.allow === true) {
+ conn.paired = [...(conn.paired ?? []), { id: request.id, name: request.name, at: Date.now() }]
+ conn.chats ??= {}
+ conn.chats[request.chatKey] ??= { kind: request.chatKind, title: request.name, at: Date.now() }
+ await rt.save()
+ const chat = conn.chats[request.chatKey]
+ const target = resolveTarget(conn, chat)
+ const name = target === undefined ? undefined : targetName(conn, target)
+ await sendTo(conn, request.chatKey, { key: request.chatKey, kind: request.chatKind, title: chat.title },
+ name === undefined ? text(request.chatKind === 'group' ? 'unboundGroup' : 'unbound') : text('connected', { target: name }))
+ } else {
+ await rt.save()
+ }
+ return true
+ },
+ async 'im-unpair'(body) {
+ const conn = connections()[String(body.id ?? '')]
+ if (conn === undefined) throw new Error('No such IM bot')
+ conn.paired = (conn.paired ?? []).filter(entry => entry.id !== String(body.senderId ?? ''))
+ await rt.save()
+ return true
+ },
+ async 'im-chat'(body) {
+ const conn = connections()[String(body.id ?? '')]
+ if (conn === undefined) throw new Error('No such IM bot')
+ const chat = conn.chats?.[String(body.chatKey ?? '')]
+ if (chat === undefined) throw new Error('No such chat')
+ if (body.remove === true) {
+ delete conn.chats[String(body.chatKey ?? '')]
+ } else if (body.target === null) {
+ delete chat.target
+ } else if (body.target !== undefined) {
+ const target = body.target
+ if (target.botId !== undefined && rt.botOf(target.botId) === undefined) throw new Error('Choose a Bot or a group')
+ if (target.roomId !== undefined && rt.roomOf(target.roomId) === undefined) throw new Error('Choose a Bot or a group')
+ chat.target = target.botId !== undefined ? { botId: String(target.botId) } : { roomId: String(target.roomId) }
+ }
+ await rt.save()
+ return true
+ },
+ async 'im-retry'(body) {
+ const conn = connections()[String(body.id ?? '')]
+ if (conn === undefined) throw new Error('No such IM bot')
+ if (runners.has(conn.id)) await stop(conn.id)
+ await sync()
+ return true
+ },
+ async 'im-login-start'() {
+ throw new Error('This platform is not available yet')
+ },
+ async 'im-login-wait'() {
+ throw new Error('This platform is not available yet')
+ },
+ }
+
+ const imEndpoint = async (endpoint, body) => {
+ const result = await endpoints[endpoint]?.(body ?? {})
+ if (result === undefined) throw new Error(`Unknown endpoint ${endpoint}`)
+ void sync()
+ void diffCards()
+ return result
+ }
+
+ // ----------------------------------------------------------------- outbound
+ // Prepended so the feed stays the last session/event listener, as its tests and
+ // the delivery order around it assume.
+ ctx.on('session/event', (session, event) => {
+ const botId = rt.chatOwners.get(session.id)
+ if (botId === undefined) return
+ for (const item of rt.displayItems(session.id, [event])) {
+ if (item.kind !== 'bot' && item.kind !== 'view') continue
+ const body = item.kind === 'bot' ? item.text : `📋 ${item.title ?? ''}`
+ for (const conn of Object.values(connections())) {
+ if (!runners.has(conn.id)) continue
+ for (const { chatKey, chat } of listeners(conn, { botId })) sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body)
+ }
+ }
+ }, { prepend: true })
+
+ rt.onRoomLine((room, line) => {
+ if (line.botId === undefined || line.kind !== undefined || typeof line.text !== 'string' || line.text.trim() === '') return
+ const body = `**${line.who}**: ${line.text}`
+ for (const conn of Object.values(connections())) {
+ if (!runners.has(conn.id)) continue
+ for (const { chatKey, chat } of listeners(conn, { roomId: room.id })) sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body)
+ }
+ })
+
+ rt.onApproval((kind, data) => {
+ if (kind === 'open') {
+ void (async () => {
+ for (const conn of Object.values(connections())) {
+ const runner = runners.get(conn.id)
+ if (runner === undefined) continue
+ const bot = rt.botOf(data.botId)
+ const targets = data.roomId !== undefined ? listeners(conn, { roomId: data.roomId }) : listeners(conn, { botId: data.botId })
+ const buttons = imPlatform(conn.platform)?.buttons === true ? cardButtons.approval(data.id) : undefined
+ await sendCard(conn, `a:${data.id}`, targets, cardText.approval(bot?.name ?? '?', data), buttons)
+ }
+ })().catch(error => rt.warn('ds-bot: im approval card failed: %s', error))
+ return
+ }
+ void (async () => {
+ for (const conn of Object.values(connections())) {
+ await settleCard(conn.id, `a:${data.id}`, data.outcome === 'allowed-once' ? text('allow') : data.outcome === 'rejected' ? text('reject') : text('answered'))
+ await settledEdits(conn)
+ }
+ })().catch(() => {})
+ })
+
+ rt.onSaved(() => {
+ void diffCards().then(settleGone).catch(() => {})
+ void sync().catch(() => {})
+ })
+
+ let interval
+ ctx.effect(() => {
+ interval = setInterval(() => {
+ void rt.refresh().then(() => sync()).catch(() => {})
+ }, RECONCILE_MS)
+ interval.unref?.()
+ void rt.load().then(() => sync()).catch(() => {})
+ return () => {
+ stopped = true
+ clearInterval(interval)
+ return Promise.all([...runners.keys()].map(stop)).then(async () => {
+ for (const held of runtimes.values()) if (held.timer !== undefined) clearTimeout(held.timer)
+ await Promise.all([...runtimes.keys()].map(writeRuntime)).catch(() => {})
+ })
+ }
+ }, 'ds-bot: im')
+
+ const imView = () => ({ connections: Object.values(connections()).map(viewOf), platforms: IM_PLATFORMS.filter(platform => adaptersFor().includes(platform.id)).map(platform => platform.id) })
+ const imStatusView = () => Object.fromEntries([...statuses.entries()].map(([id, status]) => [id, { state: status.state, ...(status.error !== undefined ? { error: status.error } : {}), at: status.at }]))
+
+ Object.assign(rt, { imView, imStatusView, imEndpoint })
+}
diff --git a/ds-bot/src/host/im/platforms/index.js b/ds-bot/src/host/im/platforms/index.js
new file mode 100644
index 00000000..a4f040f6
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/index.js
@@ -0,0 +1,5 @@
+import telegram from './telegram.js'
+
+// Every platform with an adapter. The rest of IM_PLATFORMS still show in settings as
+// coming soon — a connection can only be added for a platform listed here.
+export const adapters = { telegram }
diff --git a/ds-bot/src/host/im/platforms/telegram.js b/ds-bot/src/host/im/platforms/telegram.js
new file mode 100644
index 00000000..34f2ed28
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/telegram.js
@@ -0,0 +1,244 @@
+// Telegram Bot API adapter: getUpdates long polling in, sendMessage out. Parts of the
+// protocol mapping follow dsh-im (MIT, © 2026 xmanrui — see NOTICE).
+import { chunkTelegram } from '../format.js'
+
+const TEXT_LIMIT = 4096
+const POLL_TIMEOUT = 50
+const BACKOFF_MAX_MS = 30_000
+const UPDATES = ['message', 'callback_query']
+
+const reason = (error) => {
+ const text = [error, error?.cause].map(part => String(part?.message ?? part ?? '')).filter(Boolean).join(': ')
+ return text.slice(0, 300) || 'error'
+}
+
+const nameOf = (from) => {
+ const name = [from?.first_name, from?.last_name].filter(Boolean).join(' ').trim()
+ return from?.username ? `@${from.username}` : (name || String(from?.id ?? ''))
+}
+
+export default {
+ id: 'telegram',
+
+ async check(fields, env) {
+ const token = String(fields.token ?? '').trim()
+ if (token === '') throw new Error('Paste the bot token first')
+ const me = await callApi(env, token, 'getMe', {})
+ if (typeof me?.id !== 'number' || typeof me.username !== 'string') throw new Error('Telegram did not say who this token belongs to')
+ return { account: { id: String(me.id), name: `@${me.username}` } }
+ },
+
+ connect(fields, env, handlers) {
+ const token = String(fields.token ?? '').trim()
+ const base = `${apiBase(env)}/bot${token}`
+ const fileBase = `${apiBase(env)}/file/bot${token}`
+ let stopped = false
+ let abort
+ let selfName = ''
+
+ const call = async (method, params, { download = false, timeout = 30_000 } = {}) => {
+ abort?.abort()
+ abort = new AbortController()
+ const timer = setTimeout(() => abort.abort(new Error('timeout')), timeout)
+ try {
+ const response = await env.fetch(download ? `${fileBase}/${method}` : `${base}/${method}`, download ? { signal: abort.signal } : {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(params),
+ signal: abort.signal,
+ })
+ if (download) {
+ if (!response.ok) throw Object.assign(new Error(`Telegram answered ${response.status}`), { status: response.status, permanent: response.status >= 400 && response.status < 500 })
+ return new Uint8Array(await response.arrayBuffer())
+ }
+ const body = await response.json().catch(() => ({}))
+ if (!body.ok) {
+ const error = new Error(String(body.description ?? `Telegram answered ${response.status}`))
+ error.status = body.error_code ?? response.status
+ if (body.parameters?.retry_after !== undefined) error.retryAfter = Number(body.parameters.retry_after)
+ error.permanent = error.status >= 400 && error.status < 500 && error.status !== 429
+ throw error
+ }
+ return body.result
+ } catch (error) {
+ if (stopped) throw stoppedError()
+ if (error?.name === 'AbortError' || error?.name === 'TimeoutError') {
+ const timeout = new Error('Telegram did not answer in time')
+ timeout.unknown = true
+ throw timeout
+ }
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+ const stoppedError = () => Object.assign(new Error('stopped'), { stopped: true })
+
+ const getMe = async () => {
+ const me = await call('getMe', {})
+ selfName = me.username ? `@${me.username}` : ''
+ return me
+ }
+
+ const strip = (text) => {
+ if (selfName === '') return text
+ return text.replaceAll(selfName, ' ').replace(/\s+/g, ' ').trim()
+ }
+
+ const fileBlocks = async (message) => {
+ const images = []
+ const files = []
+ const photo = Array.isArray(message.photo) && message.photo.length > 0 ? message.photo.reduce((a, b) => ((b.file_size ?? 0) > (a.file_size ?? 0) ? b : a)) : undefined
+ if (photo !== undefined) {
+ try {
+ const file = await call('getFile', { file_id: photo.file_id })
+ const data = await call(file.file_path, {}, { download: true, timeout: 60_000 })
+ images.push({ mediaType: 'image/jpeg', data: Buffer.from(data).toString('base64') })
+ } catch (error) { env.log?.warn?.('ds-bot im: telegram photo not fetched: %s', reason(error)) }
+ }
+ const doc = message.document ?? message.voice ?? message.audio
+ if (doc?.file_id !== undefined) {
+ try {
+ const file = await call('getFile', { file_id: doc.file_id })
+ const data = await call(file.file_path, {}, { download: true, timeout: 60_000 })
+ files.push({ name: doc.file_name ?? file.file_path?.split('/').pop() ?? 'file', data })
+ } catch (error) { env.log?.warn?.('ds-bot im: telegram file not fetched: %s', reason(error)) }
+ }
+ return { images, files }
+ }
+
+ const onUpdate = async (update) => {
+ if (update.message !== undefined) {
+ const message = update.message
+ const chat = message.chat ?? {}
+ const kind = chat.type === 'private' ? 'direct' : 'group'
+ const from = message.from ?? {}
+ const raw = String(message.text ?? message.caption ?? '')
+ const mentioned = kind === 'group' && (
+ (selfName !== '' && raw.includes(selfName))
+ || (message.entities ?? []).some(entity => entity.type === 'mention' && raw.slice(entity.offset, entity.offset + entity.length) === selfName)
+ || message.reply_to_message?.from?.is_bot === true && selfName !== '' && message.reply_to_message?.from?.username === selfName.slice(1)
+ || /^\/\w+@/.test(raw) && raw.toLowerCase().includes(selfName.toLowerCase())
+ )
+ const { images, files } = await fileBlocks(message)
+ await handlers.onMessage({
+ chat: { key: String(chat.id), kind, title: chat.title ?? nameOf(from) },
+ sender: { id: String(from.id ?? ''), name: nameOf(from) },
+ text: kind === 'group' ? strip(raw) : raw,
+ images,
+ files,
+ mentioned,
+ messageId: message.message_id,
+ })
+ return
+ }
+ if (update.callback_query !== undefined) {
+ const query = update.callback_query
+ const message = query.message ?? {}
+ const chat = message.chat ?? {}
+ const from = query.from ?? {}
+ await call('answerCallbackQuery', { callback_query_id: query.id }).catch(() => {})
+ await handlers.onAction({
+ chat: { key: String(chat.id), kind: chat.type === 'private' ? 'direct' : 'group', title: chat.title ?? nameOf(from) },
+ sender: { id: String(from.id ?? ''), name: nameOf(from) },
+ data: String(query.data ?? ''),
+ messageId: message.message_id,
+ })
+ }
+ }
+
+ let delay = 0
+ const poll = async () => {
+ let me
+ try {
+ me = await getMe()
+ } catch (error) {
+ if (error.stopped) return
+ handlers.onStatus({ state: 'error', error: reason(error) })
+ return
+ }
+ handlers.onStatus({ state: 'ready', account: { id: String(me.id), name: selfName || String(me.id) } })
+ while (!stopped) {
+ try {
+ const updates = await call('getUpdates', { offset: env.runtime.get().offset ?? 0, timeout: POLL_TIMEOUT, allowed_updates: UPDATES }, { timeout: (POLL_TIMEOUT + 15) * 1000 })
+ for (const update of Array.isArray(updates) ? updates : []) {
+ if (typeof update.update_id === 'number') env.runtime.set({ offset: update.update_id + 1 })
+ await onUpdate(update).catch(error => env.log?.warn?.('ds-bot im: telegram update failed: %s', reason(error)))
+ }
+ delay = 0
+ handlers.onStatus({ state: 'ready' })
+ } catch (error) {
+ if (error.stopped || stopped) return
+ if (error.status === 409) {
+ handlers.onStatus({ state: 'error', error: 'A webhook or another program uses this bot' })
+ return
+ }
+ handlers.onStatus({ state: 'error', error: reason(error) })
+ delay = error.retryAfter !== undefined ? error.retryAfter * 1000 : Math.min(Math.max(1000, delay * 2 || 1000), BACKOFF_MAX_MS)
+ await new Promise(done => setTimeout(done, delay).unref?.())
+ }
+ }
+ }
+ void poll()
+
+ const send = async (chat, { text, buttons }) => {
+ const chunks = chunkTelegram(text, TEXT_LIMIT)
+ let messageId
+ for (const [index, chunk] of chunks.entries()) {
+ const markup = index === chunks.length - 1 && buttons?.length > 0
+ ? { reply_markup: { inline_keyboard: buttons.map(button => [{ text: button.label, callback_data: button.data }]) } }
+ : {}
+ const sendOne = async (body) => {
+ try {
+ return await call('sendMessage', { chat_id: chat.key, text: body, parse_mode: 'HTML', ...markup })
+ } catch (error) {
+ // Telegram rejects entities it cannot parse; the same text goes plain.
+ if (body !== chunk.text && /can't parse entities|parse entities/i.test(String(error?.message ?? ''))) {
+ return await call('sendMessage', { chat_id: chat.key, text: chunk.text, ...markup })
+ }
+ throw error
+ }
+ }
+ const sent = await sendOne(chunk.html)
+ messageId = sent?.message_id ?? messageId
+ }
+ return { messageId }
+ }
+
+ return {
+ send,
+ edit: async (chat, messageId, { text, buttons }) => {
+ const markup = { reply_markup: { inline_keyboard: (buttons ?? []).map(button => [{ text: button.label, callback_data: button.data }]) } }
+ try {
+ await call('editMessageText', { chat_id: chat.key, message_id: messageId, text: chunkTelegram(text, TEXT_LIMIT)[0]?.html ?? '', parse_mode: 'HTML', ...markup })
+ } catch (error) {
+ if (/can't parse entities|parse entities/i.test(String(error?.message ?? ''))) {
+ await call('editMessageText', { chat_id: chat.key, message_id: messageId, text: chunkTelegram(text, TEXT_LIMIT)[0]?.text ?? '', ...markup })
+ return
+ }
+ throw error
+ }
+ },
+ typing: chat => call('sendChatAction', { chat_id: chat.key, action: 'typing' }).catch(() => {}),
+ stop: () => {
+ stopped = true
+ abort?.abort()
+ },
+ }
+ },
+}
+
+const apiBase = env => String(env.config?.api ?? 'https://api.telegram.org').replace(/\/+$/, '')
+
+// One Bot API call without the connection's abort bookkeeping, used by `check`
+// before a connection exists.
+async function callApi(env, token, method, params) {
+ const response = await env.fetch(`${apiBase(env)}/bot${token}/${method}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(params),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (!body.ok) throw new Error(String(body.description ?? `Telegram answered ${response.status}`))
+ return body.result
+}
diff --git a/ds-bot/src/shared/im-platforms.js b/ds-bot/src/shared/im-platforms.js
new file mode 100644
index 00000000..59209bca
--- /dev/null
+++ b/ds-bot/src/shared/im-platforms.js
@@ -0,0 +1,83 @@
+// The IM platforms DS Bot can connect to. The settings page draws the add form from
+// `fields`; `secret` fields are kept as DS Bot secrets and never leave the host.
+// `buttons`: the platform can show card buttons (others answer with numbers).
+// `groups`: the IM bot can be @-mentioned in platform group chats.
+// `login: 'qr'`: the connection starts by scanning a code instead of filling fields.
+export const IM_PLATFORMS = [
+ {
+ id: 'telegram',
+ name: 'Telegram',
+ fields: [{ key: 'token', label: 'Bot token', secret: true }],
+ buttons: true,
+ groups: true,
+ help: 'https://t.me/BotFather',
+ },
+ {
+ id: 'weixin',
+ name: '微信',
+ fields: [],
+ buttons: false,
+ groups: false,
+ login: 'qr',
+ },
+ {
+ id: 'feishu',
+ name: '飞书 / Lark',
+ fields: [
+ { key: 'domain', label: 'Domain', options: [['feishu', '飞书'], ['lark', 'Lark']] },
+ { key: 'appId', label: 'App ID' },
+ { key: 'appSecret', label: 'App Secret', secret: true },
+ ],
+ buttons: true,
+ groups: true,
+ },
+ {
+ id: 'dingtalk',
+ name: '钉钉',
+ fields: [
+ { key: 'clientId', label: 'Client ID' },
+ { key: 'clientSecret', label: 'Client Secret', secret: true },
+ ],
+ buttons: false,
+ groups: true,
+ },
+ {
+ id: 'wecom',
+ name: '企业微信',
+ fields: [
+ { key: 'botId', label: 'Bot ID' },
+ { key: 'secret', label: 'Secret', secret: true },
+ ],
+ buttons: true,
+ groups: true,
+ },
+ {
+ id: 'qq',
+ name: 'QQ',
+ fields: [
+ { key: 'appId', label: 'App ID' },
+ { key: 'appSecret', label: 'App Secret', secret: true },
+ ],
+ buttons: false,
+ groups: true,
+ },
+ {
+ id: 'discord',
+ name: 'Discord',
+ fields: [{ key: 'token', label: 'Bot token', secret: true }],
+ buttons: true,
+ groups: true,
+ },
+ {
+ id: 'slack',
+ name: 'Slack',
+ fields: [
+ { key: 'appToken', label: 'App-Level Token', secret: true, hint: 'xapp-' },
+ { key: 'botToken', label: 'Bot Token', secret: true, hint: 'xoxb-' },
+ ],
+ buttons: true,
+ groups: true,
+ },
+]
+
+export const imPlatform = id => IM_PLATFORMS.find(platform => platform.id === id)
diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.js
index b29c6e0b..e31275e8 100644
--- a/ds-bot/test/bot-messages.test.js
+++ b/ds-bot/test/bot-messages.test.js
@@ -1042,7 +1042,7 @@ for (const id of ['b', 'gb']) {
ctx.llm.resolveModelInfo = async () => ({ context: { contextWindow: 192_000 } })
const preStep = async (agent) => {
agent.session.requestHeader = () => ({ config: { provider: 'custom', model: 'model' } })
- return ctx.listeners.get('agent/pre-step').at(-1)({ agent, messages: [], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
+ return ctx.listeners.get('agent/pre-step').at(0)({ agent, messages: [], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
}
const overflow = agent => fire('agent/request-error', { agent, failure: { code: 'CONTEXT_WINDOW_EXCEEDED', message: 'Tools exceed the context window' }, signal: AbortSignal.timeout(60_000) })
const waitForHandoff = async (sessionId) => {
@@ -1122,7 +1122,7 @@ for (const id of ['b', 'gb']) {
assert.ok(ctx.get('tokenMeter').measure(agent.session).totalTokens + estimateTokens(textOf(input.content)) > 50_000, 'it overflows together with the handoff')
if (pending) {
- const decision = await ctx.listeners.get('agent/pre-step').at(-1)({ agent, messages: [input], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
+ const decision = await ctx.listeners.get('agent/pre-step').at(0)({ agent, messages: [input], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
assert.deepEqual(decision, { kind: 'enter', messages: [] })
} else {
record('user/message', input)
diff --git a/ds-bot/test/fake-ctx.js b/ds-bot/test/fake-ctx.js
index 9e9a995f..1825f1b2 100644
--- a/ds-bot/test/fake-ctx.js
+++ b/ds-bot/test/fake-ctx.js
@@ -48,7 +48,7 @@ export function fakeContext({ services = {} } = {}) {
get: name => services[name],
on(name, listener, options) {
calls.push(`on ${name}${options?.prepend ? ' (prepend)' : ''}`)
- listeners.set(name, [...(listeners.get(name) ?? []), listener])
+ listeners.set(name, options?.prepend ? [listener, ...(listeners.get(name) ?? [])] : [...(listeners.get(name) ?? []), listener])
return () => {}
},
// Calls the plain listeners of an event; middleware (with `next`) is not run.
diff --git a/ds-bot/test/im-format.test.js b/ds-bot/test/im-format.test.js
new file mode 100644
index 00000000..245b4b97
--- /dev/null
+++ b/ds-bot/test/im-format.test.js
@@ -0,0 +1,38 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { chunkTelegram, toPlain, toTelegramHtml } from '../src/host/im/format.js'
+
+test('Markdown becomes Telegram HTML', () => {
+ assert.equal(toTelegramHtml('**bold** and _ital_'), '<b>bold</b> and <i>ital</i>')
+ assert.equal(toTelegramHtml('run `rm -rf` now'), 'run <code>rm -rf</code> now')
+ assert.equal(toTelegramHtml('see [the docs](https://a.b/c)'), 'see <a href="https://a.b/c">the docs</a>')
+ assert.equal(toTelegramHtml('a < b & c > d'), 'a &lt; b &amp; c &gt; d')
+ const fenced = toTelegramHtml('before\n```js\nlet x = 1 < 2\n```\nafter')
+ assert.equal(fenced, 'before\n<pre><code class="language-js">let x = 1 &lt; 2</code></pre>\nafter')
+ assert.equal(toTelegramHtml('done ~~deal~~'), 'done <s>deal</s>')
+})
+
+test('Markdown becomes plain text', () => {
+ assert.equal(toPlain('**bold** `code` [site](https://a.b)'), 'bold code site (https://a.b)')
+ assert.equal(toPlain('```\nlet x = 1\n```'), 'let x = 1')
+})
+
+test('chunks stay under the limit and keep whole fences', () => {
+ const fence = '```\n' + 'x'.repeat(200) + '\n```'
+ const chunks = chunkTelegram(`start\n\n${fence}\n\nend`, 100)
+ assert.ok(chunks.length > 1)
+ const whole = chunks.find(chunk => chunk.html.includes('<pre><code>'))
+ assert.ok(whole.html.length <= 100)
+ // The 200-char fence cannot fit, so it is split into several fenced blocks.
+ for (const chunk of chunks) assert.ok(chunk.html.length <= 100, chunk.html.length)
+ // A fence that fits is not cut.
+ const fits = chunkTelegram(`a\n\n${fence}`, 300)
+ assert.equal(fits.length, 1)
+ assert.ok(fits[0].html.includes('<pre><code>'))
+})
+
+test('an oversized line is hard cut and stays under the limit', () => {
+ const chunks = chunkTelegram('y'.repeat(9000), 4096)
+ assert.equal(chunks.length, 3)
+ for (const chunk of chunks) assert.ok(chunk.html.length <= 4096)
+})
diff --git a/ds-bot/test/im-telegram.test.js b/ds-bot/test/im-telegram.test.js
new file mode 100644
index 00000000..edad89d7
--- /dev/null
+++ b/ds-bot/test/im-telegram.test.js
@@ -0,0 +1,159 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import telegram from '../src/host/im/platforms/telegram.js'
+
+// A fake Bot API: requests are recorded and answered from `replies`; updates the
+// adapter polls come from `updates`, newest first.
+function fakeApi({ getMe = { id: 7, username: 'fakebot', is_bot: true } } = {}) {
+ const calls = []
+ const updates = []
+ const replies = {}
+ const files = {}
+ const server = createServer((req, res) => {
+ const url = new URL(req.url, 'http://x')
+ if (url.pathname.startsWith('/file/bot')) {
+ const path = url.pathname.slice('/file/botTOKEN/'.length)
+ const body = files[path]
+ if (body === undefined) { res.writeHead(404); res.end(); return }
+ res.writeHead(200, { 'content-type': 'application/octet-stream' })
+ res.end(body)
+ return
+ }
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const [, , method] = url.pathname.split('/') // /bot<token>/<method>
+ const params = JSON.parse(body || '{}')
+ calls.push({ method, params })
+ let answer = replies[method]
+ if (answer === undefined && method === 'getUpdates') answer = { result: updates.splice(0) }
+ if (answer === undefined && method === 'getMe') answer = { result: getMe }
+ if (answer === undefined && method === 'getFile') answer = { result: { file_id: params.file_id, file_path: 'photos/p1.jpg' } }
+ if (typeof answer === 'function') answer = answer(params)
+ if (answer === undefined) answer = { result: true }
+ if (answer.error) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ ok: false, error_code: answer.error, description: answer.description, parameters: answer.parameters }))
+ return
+ }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ ok: true, result: answer.result, message_id: answer.message_id ?? calls.length }))
+ })
+ })
+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => {
+ const api = `http://127.0.0.1:${server.address().port}`
+ resolve({ api, calls, updates, replies, files, close: () => server.close() })
+ }))
+}
+
+const env = (api, runtime = {}) => ({
+ fetch: globalThis.fetch,
+ config: { api },
+ runtime: { get: () => runtime, set: patch => Object.assign(runtime, patch) },
+ log: { warn: (...args) => console.error('[im-telegram]', ...args) },
+})
+
+const until = async (fn, tries = 60) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 10))
+ }
+ throw new Error('timed out waiting')
+}
+
+test('check validates the token with getMe and names the account', async () => {
+ const api = await fakeApi()
+ try {
+ const account = await telegram.check({ token: 'TOKEN' }, env(api.api))
+ assert.deepEqual(account.account, { id: '7', name: '@fakebot' })
+ assert.equal(api.calls[0].method, 'getMe')
+ await assert.rejects(telegram.check({ token: 'bad' }, { ...env(api.api), fetch: async () => ({ json: async () => ({ ok: false, error_code: 401, description: 'Unauthorized' }) }) }))
+ } finally { api.close() }
+})
+
+test('private text, group mention and photo become adapter messages', async () => {
+ const api = await fakeApi()
+ const got = { messages: [], actions: [] }
+ try {
+ api.files['photos/p1.jpg'] = Buffer.from('jpeg-bytes')
+ const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), {
+ onMessage: msg => got.messages.push(msg),
+ onAction: action => got.actions.push(action),
+ onStatus: () => {},
+ })
+ api.updates.push({ update_id: 1, message: { message_id: 11, chat: { id: 5, type: 'private' }, from: { id: 9, first_name: 'Ann', username: 'ann' }, text: 'hi there' } })
+ api.updates.push({ update_id: 2, message: { message_id: 12, chat: { id: -8, type: 'supergroup', title: 'Crew' }, from: { id: 9, first_name: 'Ann' }, text: '@fakebot look', entities: [{ type: 'mention', offset: 0, length: 8 }] } })
+ api.updates.push({ update_id: 3, message: { message_id: 13, chat: { id: 5, type: 'private' }, from: { id: 9, first_name: 'Ann' }, caption: 'see', photo: [{ file_id: 'sm', file_size: 10 }, { file_id: 'big', file_size: 99 }] } })
+ await until(() => got.messages.length >= 3)
+ const [dm, gm, photo] = got.messages
+ assert.deepEqual({ key: dm.chat.key, kind: dm.chat.kind }, { key: '5', kind: 'direct' })
+ assert.equal(dm.text, 'hi there')
+ assert.deepEqual(dm.sender, { id: '9', name: '@ann' })
+ assert.equal(gm.chat.kind, 'group')
+ assert.equal(gm.mentioned, true)
+ assert.equal(gm.text, 'look', 'the mention is stripped')
+ assert.equal(photo.images.length, 1)
+ assert.equal(photo.images[0].data, Buffer.from('jpeg-bytes').toString('base64'))
+ assert.ok(api.calls.some(call => call.method === 'getFile' && call.params.file_id === 'big'))
+ handle.stop()
+ } finally { api.close() }
+})
+
+test('callback_query answers the query and reports the action', async () => {
+ const api = await fakeApi()
+ const got = { actions: [] }
+ try {
+ const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), { onMessage: () => {}, onAction: action => got.actions.push(action), onStatus: () => {} })
+ api.updates.push({ update_id: 4, callback_query: { id: 'cq1', from: { id: 9, first_name: 'Ann' }, data: 'a:x:allow', message: { message_id: 44, chat: { id: 5, type: 'private' } } } })
+ await until(() => got.actions.length === 1)
+ assert.equal(got.actions[0].data, 'a:x:allow')
+ assert.equal(got.actions[0].messageId, 44)
+ assert.ok(api.calls.some(call => call.method === 'answerCallbackQuery' && call.params.callback_query_id === 'cq1'))
+ handle.stop()
+ } finally { api.close() }
+})
+
+test('send renders HTML, chunks long text, buttons go on the last chunk', async () => {
+ const api = await fakeApi()
+ try {
+ const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ await handle.send({ key: '5' }, { text: '**bold** ' + 'word '.repeat(1500), buttons: [{ data: 'a:1:allow', label: 'Allow once' }] })
+ const sends = api.calls.filter(call => call.method === 'sendMessage')
+ assert.equal(sends.length, 2)
+ for (const call of sends) assert.ok(call.params.text.length <= 4096, call.params.text.length)
+ assert.equal(sends[0].params.parse_mode, 'HTML')
+ assert.equal(sends[1].params.reply_markup.inline_keyboard[0][0].callback_data, 'a:1:allow')
+ handle.stop()
+ } finally { api.close() }
+})
+
+test('a chunk Telegram cannot parse goes again as plain text', async () => {
+ const api = await fakeApi()
+ try {
+ let parsed = false
+ api.replies.sendMessage = (params) => {
+ if (params.parse_mode === 'HTML' && !parsed) { parsed = true; return { error: 400, description: "Bad Request: can't parse entities" } }
+ return { result: { message_id: 7 } }
+ }
+ const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ await handle.send({ key: '5' }, { text: 'plain < enough' })
+ const sends = api.calls.filter(call => call.method === 'sendMessage')
+ assert.equal(sends.length, 2)
+ assert.equal(sends[1].params.parse_mode, undefined, 'resent without a parse mode')
+ handle.stop()
+ } finally { api.close() }
+})
+
+test('429 is honored with retry_after and 409 becomes a status error', async () => {
+ const api = await fakeApi()
+ try {
+ let hits = 0
+ api.replies.getUpdates = () => { hits += 1; return hits === 1 ? { error: 429, description: 'Too Many', parameters: { retry_after: 0 } } : { error: 409, description: 'Conflict' } }
+ const statuses = []
+ const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), { onMessage: () => {}, onAction: () => {}, onStatus: next => statuses.push(next) })
+ await until(() => statuses.some(next => next.state === 'error' && /webhook or another program/i.test(next.error ?? '')))
+ handle.stop()
+ } finally { api.close() }
+})
diff --git a/ds-bot/test/im.test.js b/ds-bot/test/im.test.js
new file mode 100644
index 00000000..cbc86524
--- /dev/null
+++ b/ds-bot/test/im.test.js
@@ -0,0 +1,391 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { test } from 'node:test'
+import { createRuntime } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+import { adapters } from '../src/host/im/platforms/index.js'
+
+// A platform adapter that records sends/edits and lets the test feed inbound
+// messages, actions and statuses. `fail` makes send throw once per call queued.
+const fakeAdapter = ({ buttons = true } = {}) => {
+ const sent = []
+ const edited = []
+ const fails = []
+ const adapter = {
+ id: 'fake',
+ sent,
+ edited,
+ handlers: null,
+ async check(fields) {
+ if (fields.token === 'bad-token') throw new Error('platform refused the token')
+ return { account: { id: 'bot1', name: '@fakebot' } }
+ },
+ connect(fields, env, handlers) {
+ adapter.handlers = handlers
+ adapter.env = env
+ handlers.onStatus({ state: 'ready', account: { id: 'bot1', name: '@fakebot' } })
+ return {
+ send: async (chat, body) => {
+ sent.push({ chat, ...body })
+ const next = fails.shift()
+ if (next !== undefined) throw next
+ return { messageId: sent.length }
+ },
+ edit: async (chat, messageId, body) => { edited.push({ chat, messageId, ...body }) },
+ typing: async () => {},
+ stop: () => { adapter.stopped = (adapter.stopped ?? 0) + 1 },
+ }
+ },
+ }
+ adapter.fails = fails
+ adapter.buttons = buttons
+ return adapter
+}
+
+const TEAM = () => ({
+ 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: 'everyone', admin: 'a', named: true, log: [], seq: 0 } },
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+})
+
+async function start({ platform = 'telegram', adapter, seed } = {}) {
+ const home = mkdtempSync(join(tmpdir(), 'dsb-im-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(seed ?? TEAM()))
+ const ctx = fakeContext()
+ const prompts = []
+ const agents = new Map()
+ const agentOf = id => {
+ if (!agents.has(id)) agents.set(id, {
+ id,
+ session: { id, requestHeader: () => undefined },
+ followup() { this.followed = (this.followed ?? 0) + 1 },
+ cancel() { this.cancelled = true },
+ inbox: { nextStep: [], nextTurn: [], remove: () => false },
+ async whenIdle() {},
+ })
+ return agents.get(id)
+ }
+ Object.assign(ctx, {
+ llm: { listProviders: () => [] },
+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async () => ({ id: 'w1' }), archiveSession: async () => {} },
+ sessionController: {
+ prompt: async (request) => { prompts.push(request); return { ok: true } },
+ resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }),
+ selectModel: async () => {},
+ },
+ sessions: { flush: async () => {} },
+ })
+ const fake = adapter ?? fakeAdapter()
+ const real = adapters[platform]
+ adapters[platform] = fake
+ const rt = createRuntime(ctx, { home })
+ const emitEvent = (sessionId, type, data) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id: sessionId }, { type, data, time: Date.now() })
+ }
+ }
+ const fireApprovals = (request, next) => Promise.all((ctx.listeners.get('approval/request') ?? [])
+ .map(listener => listener(request, next)))
+ const stop = async () => {
+ adapters[platform] = real
+ await ctx.dispose()
+ rmSync(home, { recursive: true, force: true, maxRetries: 5 })
+ }
+ const flush = async () => { await delay(10) }
+ return { ctx, rt, home, fake, prompts, agents, agentOf, emitEvent, fireApprovals, stop, flush, platform }
+}
+
+const FIELDS = { telegram: { token: 'tok-1234' }, dingtalk: { clientId: 'cli-1', clientSecret: 'sec-1234' } }
+const add = (s, fields = FIELDS[s.platform]) => s.rt.imEndpoint('im-add', { platform: s.platform, botId: 'a', fields })
+const dm = (s, senderId, text, extra = {}) => s.fake.handlers.onMessage({
+ chat: { key: `dm-${senderId}`, kind: 'direct', title: senderId }, sender: { id: senderId, name: `User ${senderId}` }, text, ...extra,
+})
+const gm = (s, senderId, text, { mentioned = true, chat = { key: 'g1', kind: 'group', title: 'Group One' }, ...extra } = {}) => s.fake.handlers.onMessage({
+ chat, sender: { id: senderId, name: `User ${senderId}` }, text, mentioned, ...extra,
+})
+
+test('unpaired DM asks once, allow pairs it, next message prompts the Bot', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ await add(s)
+ const [one] = Object.values(s.rt.state.im.connections)
+ await dm(s, 'u1', 'hello')
+ assert.equal(one.requests.length, 1)
+ assert.equal(s.fake.sent.length, 1)
+ assert.match(s.fake.sent[0].text, /connection request/)
+ assert.equal(s.prompts.length, 0)
+ await dm(s, 'u1', 'hello again')
+ assert.equal(one.requests.length, 1)
+ assert.equal(s.fake.sent.length, 1)
+ await s.rt.imEndpoint('im-pair', { id: one.id, senderId: 'u1', allow: true })
+ assert.equal(one.paired.length, 1)
+ assert.match(s.fake.sent.at(-1).text, /talk to Chief/)
+ await dm(s, 'u1', 'do a thing')
+ assert.equal(s.prompts.length, 1)
+ assert.equal(s.prompts[0].sessionId, 'a')
+ assert.equal(s.prompts[0].mode, 'queue')
+ assert.match(s.prompts[0].requestId, /^im:telegram:/)
+ assert.deepEqual(s.prompts[0].content, [{ type: 'text', text: 'do a thing' }])
+})
+
+test('unbound group mention replies unbound and records the chat; binding routes mentions', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ s.rt.state.im.connections[conn.id].paired.push({ id: 'u1', name: 'User u1', at: 1 })
+ await s.rt.save()
+ await gm(s, 'u1', 'hi all', { mentioned: false })
+ assert.equal(s.fake.sent.length, 0)
+ assert.equal(s.prompts.length, 0)
+ await gm(s, 'u1', '@fakebot hello group')
+ assert.equal(s.rt.state.im.connections[conn.id].chats.g1?.kind, 'group')
+ assert.equal(s.fake.sent.length, 1)
+ assert.match(s.fake.sent[0].text, /not bound/)
+ assert.equal(s.prompts.length, 0)
+ await s.rt.imEndpoint('im-chat', { id: conn.id, chatKey: 'g1', target: { roomId: 'r1' } })
+ // The adapter strips its own mention before the core sees the text.
+ await gm(s, 'u1', 'hello group')
+ assert.equal(s.prompts.length, 1)
+ assert.equal(s.prompts[0].sessionId, 'r1')
+ assert.deepEqual(s.prompts[0].content, [{ type: 'text', text: 'hello group' }])
+})
+
+test('outbound: assistant text and member lines go out; hidden turns, user and system lines do not', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.fake.sent.length = 0
+ s.emitEvent('a', 'assistant/message', { message: { content: [{ type: 'text', text: 'visible reply' }] } })
+ assert.equal(s.fake.sent.length, 1)
+ assert.equal(s.fake.sent[0].text, 'visible reply')
+ s.rt.state.exchangeTurns.a = [7]
+ s.emitEvent('a', 'assistant/message', { message: { content: [{ type: 'text', text: 'hidden' }] }, turn: 7 })
+ s.emitEvent('a', 'user/message', { source: { kind: 'user' }, content: [{ type: 'text', text: 'user typed' }] })
+ assert.equal(s.fake.sent.length, 1)
+ one.chats.g1 = { kind: 'group', title: 'G', target: { roomId: 'r1' }, at: 1 }
+ await s.rt.save()
+ const room = s.rt.roomOf('r1')
+ s.rt.logRoom(room, { who: 'Writer', botId: 'b', text: 'member spoke' })
+ s.rt.logRoom(room, { who: 'User', text: 'user spoke' })
+ s.rt.logRoom(room, { who: 'DS Bot', kind: 'notice', reason: 'x', text: 'nope' })
+ await s.flush()
+ assert.equal(s.fake.sent.length, 2)
+ assert.equal(s.fake.sent[1].text, '**Writer**: member spoke')
+ assert.equal(s.fake.sent[1].chat.key, 'g1')
+})
+
+test('question card: buttons answer it, a stranger press is ignored, settled elsewhere edits the card', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 }, { id: 'u2', name: 'U2', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.fake.sent.length = 0
+ s.rt.state.questions.a = { id: 'q1', question: 'Which?', options: [{ label: 'yes' }, { label: 'no' }] }
+ await s.rt.save()
+ await s.flush()
+ const card = s.fake.sent.find(entry => entry.buttons !== undefined)
+ assert.ok(card, 'question card with buttons')
+ assert.match(card.text, /Which\?/)
+ await s.fake.handlers.onAction({ chat: { key: 'dm-u2', kind: 'direct', title: 'U2' }, sender: { id: 'u9', name: 'stranger' }, data: 'q:q1:0', messageId: card.messageId ?? 1 })
+ assert.ok(s.rt.state.questions.a !== undefined, 'unpaired press does not answer')
+ await s.fake.handlers.onAction({ chat: { key: 'dm-u1', kind: 'direct', title: 'U1' }, sender: { id: 'u1', name: 'U1' }, data: 'q:q1:1', messageId: card.messageId ?? 1 })
+ assert.ok(s.rt.state.questions.a === undefined, 'paired press answers')
+ assert.equal(s.agents.get('a')?.followed, 1)
+ await s.flush()
+ assert.equal(s.fake.edited.length, 1)
+ // Answered on the computer: the question leaves the state, the card edits shut.
+ s.rt.state.questions.a = { id: 'q2', question: 'Again?', options: [{ label: 'x' }] }
+ await s.rt.save()
+ await s.flush()
+ delete s.rt.state.questions.a
+ await s.rt.save()
+ await s.flush()
+ assert.equal(s.fake.edited.length, 2)
+})
+
+test('numbered reply answers the newest open card on a no-button platform', async (t) => {
+ const s = await start({ platform: 'dingtalk', adapter: fakeAdapter({ buttons: false }) })
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.rt.state.questions.a = { id: 'q1', question: 'Pick', options: [{ label: 'x' }, { label: 'y' }] }
+ await s.rt.save()
+ await s.flush()
+ const card = s.fake.sent.at(-1)
+ assert.equal(card.buttons, undefined)
+ await dm(s, 'u1', '2')
+ assert.ok(s.rt.state.questions.a === undefined)
+ assert.equal(s.agents.get('a')?.followed, 1)
+})
+
+test('own-chat approval races DSH: IM allow resolves and withdraws the card; late press gets the stale text', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.fake.sent.length = 0
+ const original = new AbortController()
+ let seenSignal
+ const racing = s.fireApprovals(
+ { agent: { id: 'a' }, toolName: 'bash', reason: 'run it', signal: original.signal },
+ () => { seenSignal = undefined; return new Promise(() => {}) },
+ )
+ await s.flush()
+ const card = s.fake.sent.at(-1)
+ assert.match(card.text, /bash/)
+ assert.ok(card.buttons.some(button => button.data.endsWith(':allow')))
+ const approvalId = card.buttons[0].data.split(':')[1]
+ await s.fake.handlers.onAction({ chat: { key: 'dm-u1', kind: 'direct', title: 'U1' }, sender: { id: 'u1', name: 'U1' }, data: `a:${approvalId}:allow`, messageId: 1 })
+ assert.equal((await racing)[0], 'allowed-once')
+ await s.flush()
+ assert.equal(s.fake.edited.length, 1)
+ // A press after the card settled gets the stale text, not a second answer.
+ await s.fake.handlers.onAction({ chat: { key: 'dm-u1', kind: 'direct', title: 'U1' }, sender: { id: 'u1', name: 'U1' }, data: `a:${approvalId}:allow`, messageId: 1 })
+ assert.match(s.fake.sent.at(-1).text, /already answered/)
+ void seenSignal
+})
+
+test('DSH answering first settles the race; the original signal aborting cancels', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const request = { agent: { id: 'a' }, toolName: 'bash', reason: 'r', signal: new AbortController().signal }
+ const [outcome] = await s.fireApprovals(request, () => Promise.resolve('allowed-once'))
+ assert.equal(outcome, 'allowed-once')
+ const control = new AbortController()
+ const pending = s.fireApprovals({ agent: { id: 'a' }, toolName: 'bash', reason: 'r', signal: control.signal }, () => new Promise(() => {}))
+ control.abort()
+ assert.equal((await pending)[0], 'cancelled')
+})
+
+test('a pending secret request sends text without buttons', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.fake.sent.length = 0
+ s.rt.state.secretRequests = { a: [{ id: 's1', name: 'MY_KEY', purpose: 'for tests', status: 'pending', askedAt: 1 }] }
+ await s.rt.save()
+ await s.flush()
+ const card = s.fake.sent.at(-1)
+ assert.match(card.text, /MY_KEY/)
+ assert.equal(card.buttons, undefined)
+})
+
+test('a read-only host runs no adapter; becoming writable starts it', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ assert.ok(s.fake.handlers !== null)
+ const realReadOnly = s.rt.readOnly
+ s.rt.readOnly = () => 'held elsewhere'
+ await s.rt.imEndpoint('im-update', { id: conn.id, enabled: false })
+ await s.rt.imEndpoint('im-update', { id: conn.id, enabled: true })
+ assert.equal(s.fake.stopped, 1)
+ s.rt.readOnly = realReadOnly
+ await s.rt.imEndpoint('im-retry', { id: conn.id })
+ assert.ok(s.fake.handlers !== null)
+})
+
+test('/stop calls rt.stopChat for a Bot target', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ let called = 0
+ s.rt.stopChat = async () => { called += 1; return true }
+ await dm(s, 'u1', '/stop')
+ assert.equal(called, 1)
+ assert.match(s.fake.sent.at(-1).text, /Stopped|已停/)
+ await dm(s, 'u1', '/stop@fakebot')
+ assert.equal(called, 2)
+})
+
+test('im-add keeps secrets out of state, im-remove deletes them and the runtime file', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ const secretNames = Object.values(one.secrets)
+ assert.equal(secretNames.length, 1)
+ const saved = JSON.parse((await import('node:fs')).readFileSync(join(s.home, 'secrets.json'), 'utf8'))
+ assert.equal(saved.secrets[0].name, secretNames[0])
+ assert.deepEqual(saved.secrets[0].scope, [])
+ const view = s.rt.imView()
+ assert.equal(view.connections[0].id, conn.id)
+ assert.ok(!JSON.stringify(view).includes('tok-1234'))
+ await s.rt.imEndpoint('im-remove', { id: conn.id })
+ assert.equal(s.rt.state.im.connections[conn.id], undefined)
+ const after = JSON.parse((await import('node:fs')).readFileSync(join(s.home, 'secrets.json'), 'utf8'))
+ assert.equal(after.secrets.length, 0)
+ const { existsSync } = await import('node:fs')
+ assert.equal(existsSync(join(s.home, 'im', `${conn.id}.json`)), false)
+})
+
+test('a deleted Bot target gets the unbound reply', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ one.botId = 'gone'
+ await s.rt.save()
+ s.fake.sent.length = 0
+ await dm(s, 'u1', 'hi')
+ assert.match(s.fake.sent.at(-1).text, /not bound|还没绑定/)
+ assert.equal(s.prompts.length, 0)
+})
+
+test('a permanent send error shows in the status and is not retried; a network error resends in order', async (t) => {
+ const s = await start()
+ t.after(s.stop)
+ const conn = await add(s)
+ const one = s.rt.state.im.connections[conn.id]
+ one.paired.push({ id: 'u1', name: 'U1', at: 1 })
+ await s.rt.save()
+ await dm(s, 'u1', 'hi')
+ s.fake.fails.push(Object.assign(new Error('forbidden'), { status: 403, permanent: true }))
+ s.emitEvent('a', 'assistant/message', { message: { content: [{ type: 'text', text: 'will fail' }] } })
+ await s.flush()
+ assert.equal(s.rt.imStatusView()[conn.id].state, 'error')
+ assert.match(s.rt.imStatusView()[conn.id].error, /forbidden/)
+ const before = s.fake.sent.length
+ await s.flush()
+ assert.equal(s.fake.sent.length, before, 'permanent failure is not retried')
+ s.fake.fails.push(Object.assign(new Error('network down'), {}))
+ s.emitEvent('a', 'assistant/message', { message: { content: [{ type: 'text', text: 'first' }] } })
+ s.emitEvent('a', 'assistant/message', { message: { content: [{ type: 'text', text: 'second' }] } })
+ await s.flush()
+ await delay(20)
+ await s.rt.imEndpoint('im-retry', { id: conn.id })
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index fbdbba29..34c27b16 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -100,6 +100,8 @@ test('apply registers listeners and effects in a fixed order', (t) => {
'effect ds-bot: live feed route',
'route GET /api/bot/feed',
'effect ds-bot: live feed',
+ 'on session/event (prepend)',
+ 'effect ds-bot: im',
'effect ds-bot: api route',
'route POST /api/bot',
'effect ds-bot: load state',
diff --git a/ds-bot/test/scoped-tools-creation.test.js b/ds-bot/test/scoped-tools-creation.test.js
index 9711bf27..3943d227 100644
--- a/ds-bot/test/scoped-tools-creation.test.js
+++ b/ds-bot/test/scoped-tools-creation.test.js
@@ -259,7 +259,7 @@ test('a fresh part Session has the scoped tools before its first step', async (t
const moved = await host.tool('update_bot', { work_dir: project }, 'b')
assert.equal(String(moved).includes('From your next step on'), true)
// The next step sees the folder change and switches to a fresh part.
- const preStep = host.ctx.listeners.get('agent/pre-step').at(-1)
+ const preStep = host.ctx.listeners.get('agent/pre-step').at(0)
const answer = await preStep(
{ agent: host.agentOf('b'), messages: [{ role: 'user', content: [{ type: 'text', text: 'go on' }], source: { kind: 'user' } }], step: 2, signal: AbortSignal.timeout(60_000) },
async () => 'next',
diff --git a/ds-bot/test/switch-keeps-input.test.js b/ds-bot/test/switch-keeps-input.test.js
index dc941feb..b88ad1e8 100644
--- a/ds-bot/test/switch-keeps-input.test.js
+++ b/ds-bot/test/switch-keeps-input.test.js
@@ -156,7 +156,7 @@ async function start({ fail = {}, services = {}, home: reuse } = {}) {
method: 'POST', body: JSON.stringify({ endpoint, payload }),
}))).json()
const tool = (name, args, sessionId) => rt.teamTools.find(d => d.name === name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })
- const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(
+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(0)(
{ agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')
const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))
const stop = async ({ keep = false } = {}) => {
diff --git a/ds-bot/test/work-dir.test.js b/ds-bot/test/work-dir.test.js
index 3a6e71ff..d340d26f 100644
--- a/ds-bot/test/work-dir.test.js
+++ b/ds-bot/test/work-dir.test.js
@@ -114,7 +114,8 @@ async function start({ services = {}, workspaces = [], llm, team: saved = TEAM,
}))).json()
const tool = (name, args, sessionId) => rt.teamTools.find(d => d.name === name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })
// Runs the parts check, registered last; 'next' means the step goes on.
- const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(
+ // The part-transition hook registers with prepend, so it is first in the list.
+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(0)(
{ agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')
const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))
// Waits until the Bot's own chat runs in `dir` and its move has finished.
@@ -553,7 +554,7 @@ function folderService() {
}
const assemble = (ctx, agent) => {
let passed = false
- const run = ctx.listeners.get('system-prompt/assemble').at(-1)({ contexts: [] }, { agent, signal: AbortSignal.timeout(60_000) }, async () => { passed = true })
+ const run = ctx.listeners.get('system-prompt/assemble').at(0)({ contexts: [] }, { agent, signal: AbortSignal.timeout(60_000) }, async () => { passed = true })
return run.then(() => passed)
}