Skip to content

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

Send a Bot's message past 20,000 characters as a DSH file

Fei24112ad84ab1681c
diff --git a/docs/plans/2026-10-16-long-messages.md b/docs/plans/2026-10-16-long-messages.md
new file mode 100644
index 00000000..8ce03dbf
--- /dev/null
+++ b/docs/plans/2026-10-16-long-messages.md
@@ -0,0 +1,59 @@
+# 长消息
+
+- 日期:2026-10-16
+- 相关:#206;PR #258(state.json 只存开头),本文件所在的 PR(超长消息转成文件);#256(输入框粘贴变卡片)
+
+## 为什么
+
+Bot 之间的消息和群记录原来整段存进 `state.json`,而 `state.json` 每次保存都整份重写:一条 500 万字的 `message_bot` 让它涨到 6.5 MB,之后改个颜色也要重写这么多。一条消息还会整段进收件人的上下文,群里的一行会整段进每个成员的提示。PTC 程序可以把整个文件交给 `message_bot`,长度不受模型输出上限的限制。
+
+取舍:
+
+- 热文件只放有上限的数据。全文留在已经存它的地方(送达的会话),或者放进只写一次的文件。
+- 模型一次读不下的内容换成文件,让模型需要时用文件工具读,不在消息里截断。
+- 用 DSH 自己的附件库(`ctx.attachments`),不往用户的工作文件夹里写文件。
+
+## 已定的行为
+
+### state.json
+
+- 往来消息存前 2,000 字、总长度,以及全文在哪:送达的会话,或者附件。
+- 群记录的一行存前 2,000 字和总长度。成员能读到的部分(至多 20,000 字)放在 `bot/group-lines/<群>/<seq>.txt`;这一行被挤出最近 60 行、或者群被删时,文件一起删。
+- 写盘不缩进。
+- 旧数据载入时同样截短;群记录只由正在写数据的那个 DSH 搬进文件。
+
+### Bot 发出的消息
+
+- `message_bot` 和 `post_to_group` 拒绝空消息和纯空白消息。
+- 不超过 20,000 字的消息照常放在消息里。
+- 超过 20,000 字的消息原样存成 DSH 附件(内容寻址,相同内容只存一份)。消息里只留一句说明、开头 1,000 字和一个文件块;DSH 发给模型时把文件块换成只读路径。说明要求动手前先读完全文;有一行超过 2,000 字时,说明里再加一句:这些行用 shell 命令读。
+- DSH 不能存文件时,超长消息不发;工具告诉发件的 Bot 写进工作文件夹,再发路径。
+- 群里的长帖子:文件跟着这一行走,每个看到这一行的成员随提示收到文件块(和 #241 里用户发的文件一样)。
+
+### 成员读群记录
+
+- 提示里每行最多 20,000 字,超出部分写成 `… (cut; N characters in all)`。
+- `read_group_chat` 每行最多 2,000 字,被截的行给出 seq;带上 `seq` 读整行(至多 20,000 字)。
+
+### 界面
+
+- 往来记录弹窗:被截的消息显示开头和「显示全部 · N 字」,从送达的会话或附件读回,最多显示 200,000 字。
+- 群里的长帖子同样显示开头和「显示全部 · N 字」,从附件读回。
+
+### 实测
+
+- DSH 0.2.0-rc.2 + mock 模型:Bot 在 `read-only`、`workspace-write`、`danger-full-access` 三种权限预设下读附件路径,都不弹审批。
+
+## 不做什么
+
+- 不截断、不改写消息内容。附件原样保存,包括很长的行。
+- 不处理用户自己输入的长文本:输入框粘贴变卡片见 #256;用户在群里发的超长消息,成员读前 20,000 字。
+- Bot 回合里的回复(模型自己的输出)不转成文件。
+
+## 已知限制
+
+- DSH 不删除附件(DSH 写明的现有限制),记入 DSH 让步总账。只有超过 20,000 字的 Bot 消息会产生附件,相同内容只存一份。
+- DSH 的 `read` 工具每行最多显示 2,000 字,一行之内不能分页,只能靠说明提示模型用 shell 读。
+- DSH 的通用文件卡片不能打开,所以「显示全部」由 DS Bot 自己读附件。
+- 用户看到的长帖子开头带着写给模型的英文说明。
+- `group-lines/` 每个群最多 60 个文件,每个至多 20,000 字。
diff --git a/docs/plans/README.md b/docs/plans/README.md
index 84f18f11..03ebb96c 100644
--- a/docs/plans/README.md
+++ b/docs/plans/README.md
@@ -39,3 +39,4 @@
| [DSH 让步总账](2026-10-13-dsh-concessions.md) | 因 DSH 本身的限制而做的妥协,以及桌面应用之后怎么处理。判断「是 DS Bot 的 bug 还是 DSH 的限制」先看这里 |
| [角色与权限](2026-10-07-roles-and-permissions.md) | 用户、Main Bot、群管理员、普通 Bot 各能做什么;Bot 的权限预设和群的统一权限 |
| [群聊](2026-10-07-group-chat.md) | 谁来回答、按顺序发言、@ 提及、轮数上限、干活中的进度和迟到的回复、审批 |
+| [长消息](2026-10-16-long-messages.md) | state.json 只存开头;超过 2 万字的 Bot 消息转成 DSH 文件;成员和界面怎么读全文 |
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 010c171a..bc3e27bb 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -2151,9 +2151,9 @@ button.bt-q-opt:active{background:var(--bt-active)}
.bt-exchange .bt-dialog{position:relative}
.bt-exchange .bt-dialog-log{max-width:none;margin:0;padding:39px max(16px,calc((100% - 960px)/2)) 76px;scrollbar-width:thin}
.bt-exchange .bt-tools{display:none}
-.bt-exchange .bt-whole{align-self:flex-start;margin-left:30px}
-.bt-exchange .bt-whole[data-note]{cursor:default}
-.bt-exchange .bt-whole[data-note]:hover{color:var(--bt-ink-3)}
+.bt-whole{display:block;align-self:flex-start;margin-left:30px}
+.bt-whole[data-note]{cursor:default}
+.bt-whole[data-note]:hover{color:var(--bt-ink-3)}
.bt-exchange .bt-dialog-foot{position:absolute;left:0;right:0;bottom:0;height:76px;box-sizing:border-box;align-items:flex-end;padding:0 0 28px;background:var(--bt-main);z-index:3;animation:bt-foot-in .3s cubic-bezier(.22,1,.36,1) .3s both}
.bt-exchange .bt-dialog-foot::before{content:"";position:absolute;left:0;right:0;bottom:100%;height:40px;background:linear-gradient(to top,var(--bt-main),transparent);pointer-events:none}
.bt-exchange[data-leaving] .bt-dialog-foot{animation:bt-foot-out .22s cubic-bezier(.4,0,1,1) forwards}
@@ -3997,6 +3997,27 @@ function EventLine({ prefix, bots, joiner = t("and"), onOpen, whole = false }) {
});
return (0, import_react6.createElement)("div", { className: "bt-event" }, parts);
}
+function WholeNote({ length, kept, read, onShow }) {
+ if (read === void 0 || read === "loading") {
+ return (0, import_react6.createElement)("button", { type: "button", className: "bt-more bt-whole", disabled: read === "loading", onClick: onShow }, t("Show all · {count} characters", { count: length.toLocaleString() }));
+ }
+ if (read.whole) return null;
+ const note = typeof read.text === "string" && read.text.length > kept.length ? t("Showing the first {count} characters", { count: read.text.length.toLocaleString() }) : t("Only the start of this message is kept here");
+ return (0, import_react6.createElement)("span", { className: "bt-more bt-whole", "data-note": "" }, note);
+}
+function LongPost({ file, length, ...props }) {
+ const [read, setRead] = (0, import_react6.useState)();
+ const show = async () => {
+ setRead("loading");
+ setRead(await props.actions.fileText(file) ?? { whole: false });
+ };
+ return (0, import_react6.createElement)(
+ import_react6.Fragment,
+ null,
+ (0, import_react6.createElement)(GroupMessage, { ...props, text: typeof read?.text === "string" ? read.text : props.text }),
+ (0, import_react6.createElement)(WholeNote, { length, kept: props.text, read, onShow: show })
+ );
+}
function GroupMessage({ bot, text, texts: texts2 = [text], room: room2, roster, actions, msgKey, useUi }) {
const lead = (0, import_react6.createElement)(
"button",
@@ -4180,7 +4201,9 @@ function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnClock, us
if (source.failed !== void 0 || source.resumed === true || source.stopped === true) return null;
const room2 = roster.roomsById[sessionId];
const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };
- return (0, import_react6.createElement)(GroupMessage, { bot: poster, text: stripHeader(contentText(data.content)), room: room2, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi });
+ const post = { bot: poster, text: stripHeader(contentText(data.content)), room: room2, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi };
+ const file = source.length === void 0 ? void 0 : (data.content ?? []).find((block) => block?.type === "file")?.attachment;
+ return file ? (0, import_react6.createElement)(LongPost, { ...post, file, length: source.length }) : (0, import_react6.createElement)(GroupMessage, post);
}
if (source.role === "report") {
return (0, import_react6.createElement)(GroupEvent, { prefix: t("Replies from"), room: roster.roomsById[source.roomId], name: t("a group chat"), roster, actions });
@@ -8618,14 +8641,6 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
// src/client/exchange.js
var import_react21 = require("react");
var SHEET_EXIT_MS = 220;
-function WholeNote({ entry, read, onShow }) {
- if (read === void 0 || read === "loading") {
- return (0, import_react21.createElement)("button", { type: "button", className: "bt-more bt-whole", disabled: read === "loading", onClick: onShow }, t("Show all · {count} characters", { count: entry.length.toLocaleString() }));
- }
- if (read.whole) return null;
- const note = typeof read.text === "string" && read.text.length > entry.text.length ? t("Showing the first {count} characters", { count: read.text.length.toLocaleString() }) : t("Only the start of this message is kept here");
- return (0, import_react21.createElement)("span", { className: "bt-more bt-whole", "data-note": "" }, note);
-}
function ExchangeDialog({ pair, roster, actions }) {
const [entries2, setEntries] = (0, import_react21.useState)(null);
const [leaving, setLeaving] = (0, import_react21.useState)(false);
@@ -8699,7 +8714,7 @@ function ExchangeDialog({ pair, roster, actions }) {
{ className: "bt-group-msg" },
(0, import_react21.createElement)("span", { className: "bt-group-name", style: { color: inkText(colorOf(bot)) } }, bot.name),
(0, import_react21.createElement)(Bubbles, { texts: [text], roster, selfId: bot.id, actions, lead: (0, import_react21.createElement)("span", { className: "bt-lead" }, (0, import_react21.createElement)(BotMark, { bot, size: 22 })) }),
- cut ? (0, import_react21.createElement)(WholeNote, { entry, read, onShow: () => showAll(entry.id) }) : null
+ cut ? (0, import_react21.createElement)(WholeNote, { length: entry.length, kept: entry.text, read, onShow: () => showAll(entry.id) }) : null
)
);
})
@@ -13955,6 +13970,7 @@ function apply(ctx) {
scheduleDelete: (sessionId, id) => call("schedule-delete", { sessionId, id }),
exchange: (a, b) => call("exchange", { a, b }).catch(() => []),
exchangeText: (id) => call("exchange-text", { id }).catch(() => void 0),
+ fileText: (file) => call("file-text", { file }).catch(() => void 0),
roomProgress: (roomId) => call("room-progress", { roomId }).catch(() => []),
earlier: (sessionId, cursor) => call("earlier", { sessionId, cursor: cursor ?? null }),
// Hours come back in this browser's time zone, so days start at local midnight.
diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.js
index 2695e45d..bb7d62f5 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -171,6 +171,31 @@ function EventLine({ prefix, bots, joiner = t('and'), onOpen, whole = false }) {
}
// One Bot message inside a group chat: avatar, name (with its group role), bubble.
+// Under a long message that shows only its start: the button that reads it whole, or
+// why only part of it shows. `kept` is the text shown before; `read` what came back.
+export function WholeNote({ length, kept, read, onShow }) {
+ if (read === undefined || read === 'loading') {
+ return h('button', { type: 'button', className: 'bt-more bt-whole', disabled: read === 'loading', onClick: onShow }, t('Show all · {count} characters', { count: length.toLocaleString() }))
+ }
+ if (read.whole) return null
+ const note = typeof read.text === 'string' && read.text.length > kept.length
+ ? t('Showing the first {count} characters', { count: read.text.length.toLocaleString() })
+ : t('Only the start of this message is kept here')
+ return h('span', { className: 'bt-more bt-whole', 'data-note': '' }, note)
+}
+
+// A Bot's post past what a message holds came as a file: its start shows, all of it on request.
+function LongPost({ file, length, ...props }) {
+ const [read, setRead] = useState()
+ const show = async () => {
+ setRead('loading')
+ setRead(await props.actions.fileText(file) ?? { whole: false })
+ }
+ return h(Fragment, null,
+ h(GroupMessage, { ...props, text: typeof read?.text === 'string' ? read.text : props.text }),
+ h(WholeNote, { length, kept: props.text, read, onShow: show }))
+}
+
function GroupMessage({ bot, text, texts = [text], room, roster, actions, msgKey, useUi }) {
const lead = h('button', { type: 'button', className: 'bt-lead', 'aria-label': t("Open {name}'s chat", { name: bot.name }), onClick: () => actions.openSession(bot.id) },
h(BotMark, { bot, size: 22 }))
@@ -356,7 +381,9 @@ export function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnCl
if (source.failed !== undefined || source.resumed === true || source.stopped === true) return null
const room = roster.roomsById[sessionId]
const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t('a Bot'), color: 'gray' }
- return h(GroupMessage, { bot: poster, text: stripHeader(contentText(data.content)), room, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi })
+ const post = { bot: poster, text: stripHeader(contentText(data.content)), room, roster, actions, msgKey: `${sessionId}:${data.turn}:post`, useUi }
+ const file = source.length === undefined ? undefined : (data.content ?? []).find(block => block?.type === 'file')?.attachment
+ return file ? h(LongPost, { ...post, file, length: source.length }) : h(GroupMessage, post)
}
if (source.role === 'report') {
return h(GroupEvent, { prefix: t('Replies from'), room: roster.roomsById[source.roomId], name: t('a group chat'), roster, actions })
diff --git a/ds-bot/src/client/exchange.js b/ds-bot/src/client/exchange.js
index 2e1c7464..658bfa62 100644
--- a/ds-bot/src/client/exchange.js
+++ b/ds-bot/src/client/exchange.js
@@ -2,24 +2,12 @@ import { createElement as h, Fragment, useEffect, useState } from 'react'
import { inkText } from './inks.js'
import { dayLabel } from './text.js'
import { colorOf, BotMark } from './mark.js'
-import { Bubbles } from './cells.js'
+import { Bubbles, WholeNote } from './cells.js'
import { useEscape, usePaneLeft } from './overlay-hooks.js'
import { t } from './i18n.js'
const SHEET_EXIT_MS = 220
-// Under a long message: the button that reads it whole, or why only part of it shows.
-function WholeNote({ entry, read, onShow }) {
- if (read === undefined || read === 'loading') {
- return h('button', { type: 'button', className: 'bt-more bt-whole', disabled: read === 'loading', onClick: onShow }, t('Show all · {count} characters', { count: entry.length.toLocaleString() }))
- }
- if (read.whole) return null
- const note = typeof read.text === 'string' && read.text.length > entry.text.length
- ? t('Showing the first {count} characters', { count: read.text.length.toLocaleString() })
- : t('Only the start of this message is kept here')
- return h('span', { className: 'bt-more bt-whole', 'data-note': '' }, note)
-}
-
export function ExchangeDialog({ pair, roster, actions }) {
const [entries, setEntries] = useState(null)
const [leaving, setLeaving] = useState(false)
@@ -76,7 +64,7 @@ export function ExchangeDialog({ pair, roster, actions }) {
h('div', { className: 'bt-group-msg' },
h('span', { className: 'bt-group-name', style: { color: inkText(colorOf(bot)) } }, bot.name),
h(Bubbles, { texts: [text], roster, selfId: bot.id, actions, lead: h('span', { className: 'bt-lead' }, h(BotMark, { bot: bot, size: 22 })) }),
- cut ? h(WholeNote, { entry, read, onShow: () => showAll(entry.id) }) : null))
+ cut ? h(WholeNote, { length: entry.length, kept: entry.text, read, onShow: () => showAll(entry.id) }) : null))
})),
h('div', { className: 'bt-dialog-foot' }, h('button', { type: 'button', className: 'bt-soft', onClick: close }, t('Close Chat')))))
}
diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js
index 4d7e6865..88b2f7f7 100644
--- a/ds-bot/src/client/index.js
+++ b/ds-bot/src/client/index.js
@@ -551,6 +551,7 @@ export function apply(ctx) {
scheduleDelete: (sessionId, id) => call('schedule-delete', { sessionId, id }),
exchange: (a, b) => call('exchange', { a, b }).catch(() => []),
exchangeText: id => call('exchange-text', { id }).catch(() => undefined),
+ fileText: file => call('file-text', { file }).catch(() => undefined),
roomProgress: roomId => call('room-progress', { roomId }).catch(() => []),
earlier: (sessionId, cursor) => call('earlier', { sessionId, cursor: cursor ?? null }),
// Hours come back in this browser's time zone, so days start at local midnight.
diff --git a/ds-bot/src/client/styles.js b/ds-bot/src/client/styles.js
index 7aabc515..8620f77d 100644
--- a/ds-bot/src/client/styles.js
+++ b/ds-bot/src/client/styles.js
@@ -327,9 +327,9 @@ button.bt-q-opt:active{background:var(--bt-active)}
.bt-exchange .bt-dialog{position:relative}
.bt-exchange .bt-dialog-log{max-width:none;margin:0;padding:39px max(16px,calc((100% - 960px)/2)) 76px;scrollbar-width:thin}
.bt-exchange .bt-tools{display:none}
-.bt-exchange .bt-whole{align-self:flex-start;margin-left:30px}
-.bt-exchange .bt-whole[data-note]{cursor:default}
-.bt-exchange .bt-whole[data-note]:hover{color:var(--bt-ink-3)}
+.bt-whole{display:block;align-self:flex-start;margin-left:30px}
+.bt-whole[data-note]{cursor:default}
+.bt-whole[data-note]:hover{color:var(--bt-ink-3)}
.bt-exchange .bt-dialog-foot{position:absolute;left:0;right:0;bottom:0;height:76px;box-sizing:border-box;align-items:flex-end;padding:0 0 28px;background:var(--bt-main);z-index:3;animation:bt-foot-in .3s cubic-bezier(.22,1,.36,1) .3s both}
.bt-exchange .bt-dialog-foot::before{content:"";position:absolute;left:0;right:0;bottom:100%;height:40px;background:linear-gradient(to top,var(--bt-main),transparent);pointer-events:none}
.bt-exchange[data-leaving] .bt-dialog-foot{animation:bt-foot-out .22s cubic-bezier(.4,0,1,1) forwards}
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 6deb2e16..7ef06846 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -80,7 +80,7 @@ export function install(rt) {
})
// What a host that only reads the team may still answer.
// Updates change the dsh profile, not the team, so a reading host may run them too.
- const READS = new Set(['state', 'models', 'efforts', 'earlier', 'room-progress', 'exchange', 'exchange-text', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install', 'repo-stars', 'approval-answer'])
+ const READS = new Set(['state', 'models', 'efforts', 'earlier', 'room-progress', 'exchange', 'exchange-text', 'file-text', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install', 'repo-stars', 'approval-answer'])
function setPrefs(body) {
if (body.theme !== undefined) {
@@ -137,6 +137,12 @@ export function install(rt) {
if (entry === undefined) return fail('This message is no longer kept', 'bot/stale')
return ok(await rt.exchangeText(entry))
}
+ // A long Bot post's file (attachLong), for the group chat's "Show all".
+ case 'file-text': {
+ if (typeof body.file?.attachmentId !== 'string') return fail('No file named', 'bot/invalid')
+ const read = await rt.fileText(body.file)
+ return read === undefined ? fail('This file cannot be read here', 'bot/unavailable') : ok(read)
+ }
case 'earlier':
await rt.load()
return ok(await rt.earlierPage(String(body.sessionId ?? ''), body.cursor ?? undefined))
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index 85a2fc91..25b64108 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -36,6 +36,12 @@ export const TEXT_KEPT = 2000
export const GROUP_LINE_READ = 20_000
// The Bot exchange dialog shows at most this much of one message.
export const TEXT_SHOW_MAX = 200_000
+// A message a Bot sends past this goes as a DSH file, which the recipient reads with its
+// file tools; the message keeps its first LONG_HEAD characters.
+export const MESSAGE_INLINE_MAX = GROUP_LINE_READ
+export const LONG_HEAD = 1000
+// DSH's read tool shows this much of one line (dsh-tool-fs `readMaxLineLength`, default).
+export const READ_LINE_MAX = 2000
export const ROOM_REPLY_TIMEOUT_MS = 240_000
// Lines a member writes less than this apart while it works reach its group together.
export const ROOM_STEP_GAP_MS = 30_000
diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js
index a7b67dc8..acae56d0 100644
--- a/ds-bot/src/host/delivery.js
+++ b/ds-bot/src/host/delivery.js
@@ -1,7 +1,7 @@
// Delivery: how one Bot, the user, or DS Bot itself puts a message into a Bot Session.
import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
-import { HISTORY_TIMEOUT_MS, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js'
+import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js'
import { headOf, textOf } from './text.js'
export function install(rt) {
@@ -41,7 +41,8 @@ export function install(rt) {
// group turn (groups.js). `fromRoomId`: the group whose Session the sender wrote
// from; the reply goes back to that Session (turns.js). `files` go along as file
// blocks, which DSH turns into a read-only path the recipient's tools can read.
- async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, askedBy, fromRoomId, files = [] }) {
+ // `length`: the whole message's length when it went as a file (attachLong).
+ async function deliver({ fromId, toId, sessionId, text, role, hop = 0, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, askedBy, fromRoomId, files = [], length }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
@@ -67,9 +68,10 @@ export function install(rt) {
}
const targetSessionId = sessionId ?? rt.chatOf(toId)
if (EXCHANGE_ROLES.has(role) && !deferred && !resumed && !retried && !resent) {
- // The whole text is in the Session it goes to; exchangeText reads it back there.
+ // The whole text is in its file, or in the Session it goes to; exchangeText reads
+ // it back there.
const kept = headOf(text, TEXT_KEPT)
- const whole = kept.length < text.length ? { length: text.length, sessionId: targetSessionId } : {}
+ const whole = length !== undefined ? { length, files } : kept.length < text.length ? { length: text.length, sessionId: targetSessionId } : {}
state.exchanges.push({ id: exchangeId, from: fromId, to: toId, text: kept, ...whole, role, time: Date.now(), ...(replyTo ? { replyTo } : {}), ...(audience === 'user' ? { audience } : {}) })
void rt.save().catch(() => {})
}
@@ -95,6 +97,7 @@ export function install(rt) {
// be read (the Session is gone, or the message is past what the dialog shows).
async function exchangeText(entry) {
if (entry.length === undefined) return { text: entry.text, whole: true }
+ if (entry.files?.length > 0) return await fileText(entry.files[0]) ?? { text: entry.text, whole: false }
try {
for await (const event of rt.eventsBackwards(entry.sessionId ?? rt.chatOf(entry.to), AbortSignal.timeout(HISTORY_TIMEOUT_MS))) {
if (event.type !== 'user/message' || event.data?.source?.exchangeId !== entry.id) continue
@@ -108,5 +111,42 @@ export function install(rt) {
return { text: entry.text, whole: false }
}
- Object.assign(rt, { resolveAgent, deliver, exchangeText })
+ // A message a Bot sends past MESSAGE_INLINE_MAX goes as a DSH file: it is stored once,
+ // not in every Session it reaches, and the model reads it with its file tools when it
+ // needs it. Undefined when this DSH cannot store files.
+ async function attachLong(text, name) {
+ if (text.length <= MESSAGE_INLINE_MAX) return { text, files: [] }
+ try {
+ const file = await ctx.get?.('attachments')?.saveFile({ data: new TextEncoder().encode(text), name })
+ if (file === undefined) return undefined
+ // The file stays verbatim, so a line past what the read tool shows needs another way.
+ const wide = text.split('\n').some(line => line.length > READ_LINE_MAX)
+ const note = `[A long message: ${text.length} characters. Its start is below; all of it is in the attached file. Read the file before you act on it.${wide ? ` Some lines are longer than the ${READ_LINE_MAX} characters the read tool shows of a line; read those with a shell command.` : ''}]`
+ return { text: `${note}\n${headOf(text, LONG_HEAD)}…`, files: [file], length: text.length }
+ } catch (error) {
+ rt.warn('ds-bot: long message not stored as a file: %s', error)
+ return undefined
+ }
+ }
+
+ // The text of a stored file, up to what the dialogs show.
+ async function fileText(file) {
+ const attachments = ctx.get?.('attachments')
+ if (attachments === undefined) return undefined
+ const decoder = new TextDecoder()
+ let text = ''
+ try {
+ for await (const chunk of attachments.readFileStream(file, AbortSignal.timeout(HISTORY_TIMEOUT_MS))) {
+ text += decoder.decode(chunk, { stream: true })
+ if (text.length > TEXT_SHOW_MAX) return { text: headOf(text, TEXT_SHOW_MAX), whole: false }
+ }
+ } catch (error) {
+ rt.warn('ds-bot: file %s not read: %s', file?.name, error)
+ return undefined
+ }
+ text += decoder.decode()
+ return { text, whole: true }
+ }
+
+ Object.assign(rt, { resolveAgent, deliver, exchangeText, attachLong, fileText })
}
diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.js
index 5b5dae85..3750a7ce 100644
--- a/ds-bot/src/host/groups.js
+++ b/ds-bot/src/host/groups.js
@@ -483,9 +483,11 @@ export function install(rt) {
// A file stays with its line and reaches each member the line is shown to.
const readings = post.images === undefined ? [] : await rt.imagesForGroup(post.images, room.id)
const text = [post.text, ...readings, ...(post.files ?? []).map(fileLine)].filter(Boolean).join('\n')
- appendRoom(room, post.botId
- ? { who: rt.botOf(post.botId)?.name ?? post.name ?? 'Bot', botId: post.botId, text }
- : { who: 'User', text, ...(post.files === undefined ? {} : { files: post.files }) })
+ appendRoom(room, {
+ ...(post.botId ? { who: rt.botOf(post.botId)?.name ?? post.name ?? 'Bot', botId: post.botId } : { who: 'User' }),
+ text,
+ ...(post.files === undefined ? {} : { files: post.files }),
+ })
}
if (posts.some(post => !post.botId && !post.kickoff)) {
room.botRounds = 0
@@ -658,10 +660,10 @@ export function install(rt) {
}
// A Bot's message into the group's own Session, which relays it as a new round.
- async function postToRoom(room, sender, text, extra = {}) {
+ async function postToRoom(room, sender, text, extra = {}, files = []) {
const agent = await rt.resolveAgent(room.id)
agent.followup(createUserMessage({
- content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }],
+ content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }, ...files.map(attachment => ({ type: 'file', attachment }))],
source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, hop: 0, ...extra },
}))
await ctx.sessions.flush(agent.session)
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 28cc925b..41fa9046 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -2,7 +2,7 @@
// question card. Group rounds and reading chats are in groups.js.
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
-import { COLORS, EXTRA_COLORS, MAX_HOPS, MAX_UNATTENDED_MESSAGES, MAX_UNREAD_REQUESTS, ROOM_BOT_ROUNDS, ROOM_MODES, SOURCE_KIND } from './constants.js'
+import { COLORS, EXTRA_COLORS, MAX_HOPS, MAX_UNATTENDED_MESSAGES, MAX_UNREAD_REQUESTS, MESSAGE_INLINE_MAX, ROOM_BOT_ROUNDS, ROOM_MODES, SOURCE_KIND } from './constants.js'
import { unquote } from './text.js'
export const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] }
@@ -95,6 +95,7 @@ export function install(rt) {
return 1 + Math.max(turn?.info?.hop ?? 0, ...(turn?.joined ?? []).map(joined => joined.info?.hop ?? 0))
}
const CHAIN_TOO_LONG = 'This chain of Bot messages is already long. Stop here and report to the user instead.'
+ const tooLong = text => `Not sent: the message has ${text.length} characters, more than ${MESSAGE_INLINE_MAX}, and this DeepSeek Harness cannot send it as a file. Write it to a file in your working folder and send its path instead.`
const checkUnattended = () => {
if (rt.unattended.sent < MAX_UNATTENDED_MESSAGES) return
refuse(`Not sent: the team has sent ${MAX_UNATTENDED_MESSAGES} Bot messages since the user last wrote. Stop messaging other Bots and tell the user what is still open.`)
@@ -134,10 +135,12 @@ export function install(rt) {
if (unread >= MAX_UNREAD_REQUESTS) {
refuse(`Not sent: ${target.name} has not read the last ${unread} messages from Bots yet, so it is most likely stuck, for example waiting for the user. Do not send it more; tell the user that ${target.name} is not responding.`)
}
+ const long = await rt.attachLong(String(args.message), `Message from ${sender.name}.txt`)
+ if (long === undefined) return tooLong(String(args.message))
const toUser = args.reply_to === 'user'
const working = rt.live.get(chat)?.turn !== undefined
const steer = args.when !== 'queue' && !toUser
- await rt.deliver({ fromId: sender.id, toId: target.id, text: args.message, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : callerRoom(exec)) })
+ await rt.deliver({ fromId: sender.id, toId: target.id, text: long.text, files: long.files, length: long.length, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : callerRoom(exec)) })
rt.unattended.sent += 1
const sent = toUser
? `Delivered to ${target.name}. It will answer the user in its own chat; nothing comes back to you, so point the user to ${target.name}'s chat instead of relaying.`
@@ -423,11 +426,13 @@ export function install(rt) {
if (text === '') return 'Write a message to post.'
if ((room.botRounds ?? 0) >= ROOM_BOT_ROUNDS) return `Bots already started ${ROOM_BOT_ROUNDS} rounds in "${room.name}" since the user last spoke there. Wait for the user.`
checkUnattended()
+ const long = await rt.attachLong(text, `Post from ${sender.name}.txt`)
+ if (long === undefined) return tooLong(text)
room.botRounds = (room.botRounds ?? 0) + 1
await rt.save()
const reportBack = args.report_back === true
try {
- await rt.postToRoom(room, sender, text, { hop, ...(reportBack ? { reportBack: true } : {}) })
+ await rt.postToRoom(room, sender, long.text, { hop, ...(reportBack ? { reportBack: true } : {}), ...(long.length ? { length: long.length } : {}) }, long.files)
} catch (failure) {
return `Could not post in "${room.name}": ${failure.message}`
}
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index ea08bc29..55032393 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -371,8 +371,11 @@ export function install(rt) {
}
}
if (source?.kind === SOURCE_KIND && source.role === 'post' && rt.roomOf(id)) {
+ // A long post comes as a file (attachLong), which stays with its line.
+ const files = (Array.isArray(event.data.content) ? event.data.content : []).filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment)
queueRoomMessage(id, {
text: textOf(event.data.content).replace(/^\[Group post from [^\]]*\]\n?/, ''),
+ ...(files.length > 0 ? { files } : {}),
botId: source.senderSessionId,
name: source.senderName,
reportBack: source.reportBack === true,
diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.js
index 3646fcde..ef62204b 100644
--- a/ds-bot/test/bot-messages.test.js
+++ b/ds-bot/test/bot-messages.test.js
@@ -5,7 +5,7 @@ import { join } from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
import { test } from 'node:test'
import { apply } from '../index.js'
-import { fakeContext } from './fake-ctx.js'
+import { fakeAttachments, fakeContext } from './fake-ctx.js'
import { install as installTurns } from '../src/host/turns.js'
import { install as installParts } from '../src/host/parts.js'
import { MAX_HOPS, MAX_UNATTENDED_MESSAGES, REPLY_KIND, SOURCE_KIND } from '../src/host/constants.js'
@@ -635,7 +635,7 @@ test('message_bot turns down an empty message', async (t) => {
test('a long message between Bots keeps its start in state.json and is read back whole from the Session', async (t) => {
const { ctx, agentOf, tool, call, exchanges, home, stop } = await start(team())
t.after(stop)
- const long = `${'长'.repeat(30_000)}结尾`
+ const long = `${'长'.repeat(15_000)}结尾`
await tool('message_bot', { to: 'Writer', message: long }, 'a')
const [, delivered] = agentOf('b').calls.find(([kind]) => kind === 'steer' || kind === 'followup')
assert.ok(delivered.content[0].text.endsWith(long), 'the recipient gets it whole')
@@ -670,3 +670,52 @@ test('a team saved with long messages whole keeps only their start after it load
assert.equal(entry.text, 'y'.repeat(2000))
assert.equal(entry.length, 5000)
})
+
+// #206: a message past 20,000 characters went whole into every Session it reached and
+// into the model's context at once. It now goes as a DSH file the recipient reads.
+test('a message past 20,000 characters goes as a file, which the exchange dialog reads back', async (t) => {
+ const { ctx, agentOf, tool, call, exchanges, stop } = await start(team())
+ t.after(stop)
+ const store = fakeAttachments()
+ ctx.get = name => (name === 'attachments' ? store : undefined)
+ const lines = Array.from({ length: 400 }, (_, at) => `第 ${at + 1} 行:${'长消息的一行。'.repeat(8)}`)
+ const long = `${lines.join('\n')}\n结尾`
+ assert.ok(long.length > 20_000)
+ const answer = await tool('message_bot', { to: 'Writer', message: long }, 'a')
+ assert.match(answer, /^Delivered to Writer/)
+ const [, delivered] = agentOf('b').calls.find(([kind]) => kind === 'steer' || kind === 'followup')
+ const [text, file] = delivered.content
+ assert.ok(text.text.startsWith(`[Message from Chief]\n[A long message: ${long.length} characters. Its start is below; all of it is in the attached file. Read the file before you act on it.]\n第 1 行`))
+ assert.ok(!text.text.includes('shell command'), 'no line is past what the read tool shows')
+ assert.ok(text.text.length < 1200)
+ assert.equal(file.type, 'file')
+ assert.equal(file.attachment.name, 'Message from Chief.txt')
+ assert.equal(new TextDecoder().decode(store.files.get(file.attachment.attachmentId)), long)
+
+ const [entry] = await exchanges()
+ assert.equal(entry.length, long.length)
+ assert.deepEqual(entry.files, [file.attachment])
+ assert.deepEqual((await call('exchange-text', { id: entry.id })).value, { text: long, whole: true })
+ assert.deepEqual((await call('file-text', { file: file.attachment })).value, { text: long, whole: true })
+})
+
+test('a long message with a line past what the read tool shows says how to read it', async (t) => {
+ const { ctx, agentOf, tool, stop } = await start(team())
+ t.after(stop)
+ ctx.get = name => (name === 'attachments' ? fakeAttachments() : undefined)
+ await tool('message_bot', { to: 'Writer', message: 'x'.repeat(25_000) }, 'a')
+ const [, delivered] = agentOf('b').calls.find(([kind]) => kind === 'steer' || kind === 'followup')
+ assert.match(delivered.content[0].text, /Some lines are longer than the 2000 characters the read tool shows of a line; read those with a shell command\./)
+})
+
+test('without file storage a message past 20,000 characters is not sent', async (t) => {
+ const { agentOf, tool, exchanges, stop } = await start(team())
+ t.after(stop)
+ const answer = await tool('message_bot', { to: 'Writer', message: 'x'.repeat(20_001) }, 'a')
+ assert.equal(answer, 'Not sent: the message has 20001 characters, more than 20000, and this DeepSeek Harness cannot send it as a file. Write it to a file in your working folder and send its path instead.')
+ assert.deepEqual(agentOf('b').calls, [])
+ assert.deepEqual(await exchanges(), [])
+ // 20,000 characters still go as they are.
+ await tool('message_bot', { to: 'Writer', message: 'x'.repeat(20_000) }, 'a')
+ assert.equal(agentOf('b').calls.length, 1)
+})
diff --git a/ds-bot/test/fake-ctx.js b/ds-bot/test/fake-ctx.js
index 62fed26b..8e30e0bb 100644
--- a/ds-bot/test/fake-ctx.js
+++ b/ds-bot/test/fake-ctx.js
@@ -1,3 +1,22 @@
+// DSH's `attachments` service for generic files, in memory. Reads come back in small
+// chunks that split characters, as a stream may.
+export function fakeAttachments() {
+ const files = new Map()
+ return {
+ files,
+ async saveFile({ data, name }) {
+ const ref = { attachmentId: `sha256:${files.size + 1}`, name, bytes: data.length }
+ files.set(ref.attachmentId, data)
+ return ref
+ },
+ async* readFileStream(ref) {
+ const data = files.get(ref.attachmentId)
+ if (data === undefined) throw new Error('no such file')
+ for (let at = 0; at < data.length; at += 1001) yield data.subarray(at, at + 1001)
+ },
+ }
+}
+
// A stand-in for the plugin context that records what apply() registers, in order,
// without starting any service.
export function fakeContext({ services = {} } = {}) {
diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.js
index e3b57d67..196c8ea3 100644
--- a/ds-bot/test/rounds.test.js
+++ b/ds-bot/test/rounds.test.js
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import { createRuntime } from '../index.js'
-import { fakeContext } from './fake-ctx.js'
+import { fakeAttachments, fakeContext } from './fake-ctx.js'
// A fake team of two Bots in one group; member answers are played back through the
// session/event listener, so a round runs with no model. Prompts land in the
@@ -455,3 +455,36 @@ test('a file the user sends in a group reaches each member the line is shown to,
await running
})
+// #206: a Bot's post past 20,000 characters goes as a file; the line keeps the file and
+// each member it is shown to gets it with its prompt.
+test('a long post goes to the group as a file, and reaches the member with its prompt', async (t) => {
+ const { call, emit, relay, answer, stop, sent, ctx, rt } = start()
+ t.after(stop)
+ const store = fakeAttachments()
+ ctx.get = name => (name === 'attachments' ? store : undefined)
+ const room = await team(call, sent)
+ const chief = rt.state.mainBotIds[0]
+ const long = `${Array.from({ length: 400 }, (_, at) => `第 ${at + 1} 行:${'报告内容。'.repeat(10)}`).join('\n')}\n结尾`
+ const posted = await ctx.registeredTools.get('post_to_group').execute({ group: 'R1', message: long }, { agent: { id: rt.chatOf(chief) } })
+ assert.match(posted, /^Posted in "R1"/)
+ const post = sent.find(entry => entry.sessionId === room.id && entry.message.source.role === 'post')
+ const file = post.message.content.find(block => block.type === 'file')?.attachment
+ assert.equal(file?.name, 'Post from Chief.txt')
+ assert.equal(post.message.source.length, long.length)
+ assert.equal(new TextDecoder().decode(store.files.get(file.attachmentId)), long)
+
+ sent.length = 0
+ await emit(room.id, { type: 'user/message', data: { source: post.message.source, content: post.message.content } })
+ const running = relay(room.id, 'relay')
+ const turn = await turnFor(sent)
+ assert.deepEqual(turn.message.content.filter(block => block.type === 'file').map(block => block.attachment), [file])
+ const prompt = turn.message.content[0].text
+ assert.ok(prompt.includes(`Chief: [A long message: ${long.length} characters.`))
+ assert.ok(prompt.includes(`[File "Post from Chief.txt" (${file.bytes} bytes) attached]`))
+ assert.ok(prompt.length < 6000, `the prompt has ${prompt.length} characters`)
+ await answer(turn.sessionId, turn.message.source.exchangeId, 'Read it.', 1)
+ await running
+ const line = rt.state.rooms[room.id].log.find(entry => entry.botId === chief)
+ assert.deepEqual(line.files, [file])
+ assert.equal(line.length, undefined, 'the line is short; no file of its own')
+})