@xmanrui/dsh-im 5.7.0 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.en.md +42 -7
  2. package/README.md +53 -7
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +375 -160
  5. package/lib/index.js +330 -325
  6. package/package.json +3 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/connection-error.js +1 -1
  11. package/plugin-src/client/delivery-settings.js +4 -0
  12. package/plugin-src/client/i18n-ru.js +17 -0
  13. package/plugin-src/client/i18n.js +17 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  18. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  19. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  20. package/plugin-src/host/channels/qq/production.mjs +2 -1
  21. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  22. package/plugin-src/host/channels/shared/production.mjs +32 -3
  23. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  24. package/plugin-src/host/channels/slack/production.mjs +2 -1
  25. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  26. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  27. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  28. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  29. package/plugin-src/host/delivery-adapter.mjs +122 -1
  30. package/plugin-src/host/delivery-service.mjs +40 -0
  31. package/plugin-src/host/ds-bot-client.mjs +28 -2
  32. package/plugin-src/host/index.mjs +24 -1
  33. package/plugin-src/host/modern-harness-api.mjs +3 -0
  34. package/scripts/telegram-menu-scopes.mjs +57 -0
  35. package/scripts/verify-interface-language.mjs +60 -15
  36. package/scripts/verify-package.mjs +17 -6
  37. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  38. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  39. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  40. package/src/channels/feishu/bridge.mjs +75 -22
  41. package/src/channels/feishu/feishu-cards.mjs +96 -25
  42. package/src/channels/feishu/message-utils.mjs +1 -0
  43. package/src/channels/qq/qq-menu.mjs +3 -4
  44. package/src/channels/shared/action-card.mjs +331 -0
  45. package/src/channels/shared/bot-workspace-store.mjs +369 -6
  46. package/src/channels/shared/command-catalog.mjs +20 -5
  47. package/src/channels/shared/conversation/describe.mjs +116 -0
  48. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  49. package/src/channels/shared/conversation-directory.mjs +29 -0
  50. package/src/channels/shared/conversation-state-store.mjs +62 -0
  51. package/src/channels/shared/diagnostic-details.mjs +38 -0
  52. package/src/channels/shared/harness-approval.mjs +58 -13
  53. package/src/channels/shared/harness-client.mjs +85 -2
  54. package/src/channels/shared/harness-session-binding.mjs +13 -1
  55. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  56. package/src/channels/shared/i18n-en/feishu.mjs +6 -0
  57. package/src/channels/shared/i18n-en/shared-a.mjs +14 -0
  58. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  59. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  60. package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
  61. package/src/channels/shared/i18n-ru/shared-a.mjs +14 -0
  62. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  63. package/src/channels/shared/message-failure.mjs +8 -0
  64. package/src/channels/shared/model-command.mjs +5 -0
  65. package/src/channels/shared/new-command.mjs +7 -0
  66. package/src/channels/shared/preset-workspaces.mjs +48 -0
  67. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  68. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  69. package/src/channels/shared/status-command.mjs +159 -0
  70. package/src/channels/shared/text-harness-bridge.mjs +89 -6
  71. package/src/channels/shared/workspace-command.mjs +36 -15
  72. package/src/channels/shared/workspace-session.mjs +30 -5
  73. package/src/channels/telegram/approval-card.mjs +379 -0
  74. package/src/channels/telegram/telegram-api.mjs +10 -1
  75. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  76. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  77. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -53,13 +53,24 @@ function sessionWorkspace(sessionId, value) {
53
53
  };
54
54
  }
55
55
 
56
- function sessionSummary(sessionId, value) {
56
+ /**
57
+ * @param {string} sessionId - the id the command asked for
58
+ * @param {object} value - the `session.list` response
59
+ * @param {boolean} knownToWorkspace - whether `workspace.list` already accounts for it
60
+ */
61
+ function sessionSummary(sessionId, value, knownToWorkspace = false) {
57
62
  if (!Array.isArray(value?.items)
58
63
  || value.items.some((item) => typeof item?.sessionId !== 'string' || !item.sessionId)) {
59
64
  throw new Error('Harness returned an invalid response for session.list');
60
65
  }
61
66
  const matches = value.items.filter((item) => item.sessionId === sessionId);
62
67
  if (matches.length === 0) {
68
+ // An id nobody ever registered is not a transient read failure: a workspace
69
+ // that accounts for the session but has no summary yet may still appear, so
70
+ // only the pair of answers means "no such session".
71
+ if (!knownToWorkspace) {
72
+ throw bindingError('session-not-registered', 'No session with this id is known to Harness');
73
+ }
63
74
  throw bindingError('session-summary-unavailable', 'The session is no longer available from Harness');
64
75
  }
65
76
  if (matches.length !== 1) {
@@ -91,6 +102,7 @@ export async function adoptRegisteredWorkspaceSession(client, value, options = {
91
102
  const summary = sessionSummary(
92
103
  sessionId,
93
104
  await client.rpc('session.list', {}, timeoutMs, options),
105
+ workspace !== undefined || archived === true,
94
106
  );
95
107
  if (!workspace) {
96
108
  if (typeof summary.cwd !== 'string' || !isAbsolute(summary.cwd)
@@ -28,6 +28,8 @@ export default Object.freeze({
28
28
  'Message preparation failed before submission. It has not been submitted for execution. Try again; if this persists, share the reference with your administrator.',
29
29
  '消息已尝试提交,但任务结果尚未确认。请先到 DSH 查看状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
30
30
  'Message submission was attempted, but the task outcome is unconfirmed. Check its status in DSH before resubmitting; if this persists, share the reference with your administrator.',
31
+ '消息提交请求超时,未能确认消息是否已送达 DSH。请稍后到 DSH 查看该会话状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
32
+ 'The message submission request timed out and delivery to DSH could not be confirmed. Check the session status in DSH before resubmitting; if this persists, share the reference with your administrator.',
31
33
  "DSH 版本": "DSH version",
32
34
  "依赖版本": "Dependency versions",
33
35
  "代理已配置": "Proxy configured",
@@ -187,6 +187,12 @@ export default {
187
187
  '跟随默认': 'Follow default',
188
188
  '切换预设': 'Switch preset',
189
189
  '切换模型': 'Switch model',
190
+ '默认等级': 'Default effort',
191
+ '切换推理等级': 'Switch reasoning effort',
192
+ '第 {page}/{pages} 页 · 共 {total} 个模型': 'Page {page}/{pages} · {total} models',
193
+ '第一页': 'First page',
194
+ '最后一页': 'Last page',
195
+ '当前模型不可用:{model}': 'Current model is unavailable: {model}',
190
196
  '当前工作区暂无可用会话。': 'There are no available sessions in the current workspace.',
191
197
  '🤖 切换预设': '🤖 Switch preset',
192
198
  '🧠 切换模型': '🧠 Switch model',
@@ -1,5 +1,10 @@
1
1
  // English translations (shared-a area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请发送你的问题。': 'Please send your question.',
4
+ '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。':
5
+ 'Conversation directory isolation did not take effect: the directory could not be created. This session will use the original workspace.',
6
+ '会话目录未生效:无法切换目录;本次仍在原工作区运行。':
7
+ 'Conversation directory isolation did not take effect: the directory could not be selected. This session will use the original workspace.',
3
8
  '这个问题已在其他客户端处理,无需再次回答。':
4
9
  'This question has already been answered from another client; no further reply is needed.',
5
10
  '任务已完成。': 'Task completed.',
@@ -211,6 +216,15 @@ export default {
211
216
  '/help 显示本帮助': '/help Show this help',
212
217
  '{label}机器人与 DeepSeek Harness 连接正常。':
213
218
  'The {label} bot is connected to DeepSeek Harness and working normally.',
219
+ // /status details (shared by every text channel that uses TextHarnessBridge).
220
+ '绑定会话:{session}': 'Session: {session}',
221
+ '绑定会话:未绑定(发送消息后自动创建)':
222
+ 'Session: not bound yet (created after you send a message)',
223
+ '当前模型:暂无(创建会话后显示)':
224
+ 'Current model: not available yet (shown after a Session is created)',
225
+ 'Agent Preset(预设):{preset}': 'Agent Preset: {preset}',
226
+ '运行中任务:有(发送 /stop 可停止)':
227
+ 'Running task: yes (send /stop to stop it)',
214
228
  '{label}机器人凭据缺失,请移除后重新接入。':
215
229
  '{label} bot credentials are missing. Remove the bot and connect it again.',
216
230
  '{label}连接未就绪,插件会自动重试。':
@@ -30,4 +30,18 @@ export default {
30
30
  'This Telegram bot already has a Webhook configured. Remove the Webhook from the original service and try again.',
31
31
  'Telegram机器人': 'Telegram Bot',
32
32
  ' Bot API 长轮询': ' Bot API long polling',
33
+ // Approval button card (batch 1): buttons, terminal receipts and dead-card
34
+ // notices. Keys match the literals passed through t() in approval-card.mjs.
35
+ '✅ 批准一次': '✅ Approve once',
36
+ '✅ 已批准(仅本次)': '✅ Approved (this time only)',
37
+ '❌ 已拒绝': '❌ Rejected',
38
+ '⏰ 已过期': '⏰ Expired',
39
+ '⛔ 已失效': '⛔ No longer valid',
40
+ '正在提交审批决定,请稍候。': 'Submitting the approval decision, please wait.',
41
+ '该审批已处理,无需重复操作。': 'This approval was already handled. No need to act again.',
42
+ '该审批已过期,已自动拒绝。': 'This approval expired and was rejected automatically.',
43
+ '该审批已被新提示取代,请使用最新一条。':
44
+ 'This approval was superseded by a newer prompt; use the latest one.',
45
+ '该审批已失效,请等待新的审批提示。':
46
+ 'This approval is no longer valid; wait for a new approval prompt.',
33
47
  };
@@ -28,6 +28,8 @@ export default Object.freeze({
28
28
  'Обработка сообщения до отправки не удалась, на выполнение оно не ушло. Повторите попытку; если ошибка повторяется, передайте администратору номер обращения.',
29
29
  '消息已尝试提交,但任务结果尚未确认。请先到 DSH 查看状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
30
30
  'Сообщение отправлено, но результат задачи пока не подтверждён. Сначала проверьте состояние в DSH и не отправляйте повторно; если ошибка повторяется, передайте администратору номер обращения.',
31
+ '消息提交请求超时,未能确认消息是否已送达 DSH。请稍后到 DSH 查看该会话状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
32
+ 'Время ожидания запроса на отправку сообщения истекло, и доставку в DSH подтвердить не удалось. Позже проверьте состояние этой сессии в DSH и не отправляйте сообщение повторно сразу; если ошибка повторяется, передайте администратору номер обращения.',
31
33
  'DSH 版本': 'Версия DSH',
32
34
  '依赖版本': 'Версии зависимостей',
33
35
  '代理已配置': 'Прокси настроен',
@@ -166,6 +166,12 @@ export default {
166
166
  '跟随默认': 'Как по умолчанию',
167
167
  '切换预设': 'Сменить пресет',
168
168
  '切换模型': 'Сменить модель',
169
+ '默认等级': 'По умолчанию',
170
+ '切换推理等级': 'Сменить уровень рассуждений',
171
+ '第 {page}/{pages} 页 · 共 {total} 个模型': 'Страница {page}/{pages} · моделей: {total}',
172
+ '第一页': 'Первая страница',
173
+ '最后一页': 'Последняя страница',
174
+ '当前模型不可用:{model}': 'Текущая модель недоступна: {model}',
169
175
  '当前工作区暂无可用会话。': 'В текущей рабочей области нет доступных сессий.',
170
176
  '🤖 切换预设': '🤖 Сменить пресет',
171
177
  '🧠 切换模型': '🧠 Сменить модель',
@@ -1,5 +1,10 @@
1
1
  // Russian translations (shared-a area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请发送你的问题。': 'Отправьте свой вопрос.',
4
+ '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。':
5
+ 'Изоляция каталога беседы не применена: не удалось создать каталог (недостаточно прав или места на диске). Этот сеанс продолжит работу в исходной рабочей области.',
6
+ '会话目录未生效:无法切换目录;本次仍在原工作区运行。':
7
+ 'Изоляция каталога беседы не применена: не удалось переключить каталог. Этот сеанс продолжит работу в исходной рабочей области.',
3
8
  '这个问题已在其他客户端处理,无需再次回答。':
4
9
  'На этот вопрос уже ответили в другом клиенте, повторять ответ не нужно.',
5
10
  '任务已完成。': 'Задача выполнена.',
@@ -206,6 +211,15 @@ export default {
206
211
  '/version 查看插件版本': '/version Показать версию плагина',
207
212
  '/help 显示本帮助': '/help Показать эту справку',
208
213
  '{label}机器人与 DeepSeek Harness 连接正常。': 'Бот {label} и DeepSeek Harness соединены нормально.',
214
+ // /status details (shared by every text channel that uses TextHarnessBridge).
215
+ '绑定会话:{session}': 'Сессия: {session}',
216
+ '绑定会话:未绑定(发送消息后自动创建)':
217
+ 'Сессия: ещё не привязана (создаётся после вашего сообщения)',
218
+ '当前模型:暂无(创建会话后显示)':
219
+ 'Текущая модель: пока недоступна (появится после создания сессии)',
220
+ 'Agent Preset(预设):{preset}': 'Agent Preset: {preset}',
221
+ '运行中任务:有(发送 /stop 可停止)':
222
+ 'Выполняется задача: да (отправьте /stop, чтобы остановить)',
209
223
  '{label}机器人凭据缺失,请移除后重新接入。': 'Нет учётных данных бота {label}. Удалите его и подключите заново.',
210
224
  '{label}连接未就绪,插件会自动重试。': 'Соединение {label} не готово, плагин повторит попытку автоматически.',
211
225
  '{label}机器人已接入,消息连接暂未就绪。': 'Бот {label} подключён, но соединение для сообщений пока не готово.',
@@ -27,4 +27,18 @@ export default {
27
27
  'У этого бота Telegram уже настроен Webhook. Удалите Webhook в исходном сервисе и повторите попытку.',
28
28
  'Telegram机器人': 'Бот Telegram',
29
29
  ' Bot API 长轮询': ' Долгий опрос Bot API',
30
+ // Approval button card (batch 1): buttons, terminal receipts and dead-card
31
+ // notices. Keys match the literals passed through t() in approval-card.mjs.
32
+ '✅ 批准一次': '✅ Одобрить один раз',
33
+ '✅ 已批准(仅本次)': '✅ Одобрено (только в этот раз)',
34
+ '❌ 已拒绝': '❌ Отклонено',
35
+ '⏰ 已过期': '⏰ Просрочено',
36
+ '⛔ 已失效': '⛔ Больше не действует',
37
+ '正在提交审批决定,请稍候。': 'Отправляю решение о подтверждении, подождите.',
38
+ '该审批已处理,无需重复操作。': 'Это подтверждение уже обработано. Повторять не нужно.',
39
+ '该审批已过期,已自动拒绝。': 'Срок подтверждения истёк, операция отклонена автоматически.',
40
+ '该审批已被新提示取代,请使用最新一条。':
41
+ 'Это подтверждение заменено более новым запросом. Используйте последний.',
42
+ '该审批已失效,请等待新的审批提示。':
43
+ 'Это подтверждение больше не действует. Дождитесь нового запроса.',
30
44
  };
@@ -26,6 +26,11 @@ const PROVIDER_FAILURES = Object.freeze({
26
26
  UNSUPPORTED_CONTENT: 'MODEL_CONFIG',
27
27
  });
28
28
 
29
+ // 提交超时(stage=prompt.submit 且 harness-timeout)单列文案:与「已提交、结果
30
+ // 未知」区分,明确「提交请求本身超时、是否送达未知」,避免用户误以为任务已运行。
31
+ const PROMPT_SUBMIT_UNCONFIRMED_MESSAGE =
32
+ '消息提交请求超时,未能确认消息是否已送达 DSH。请稍后到 DSH 查看该会话状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。';
33
+
29
34
  const FAILURE_MESSAGES = Object.freeze({
30
35
  HARNESS_INTERACTION_TIMEOUT:
31
36
  '与 DSH 的交互通道在 30 秒内未就绪,本条消息尚未提交执行。请稍后重试。',
@@ -230,6 +235,9 @@ export function classifyMessageFailure(error, {
230
235
  if (code === 'REQUEST_TIMEOUT' || code === 'NETWORK_ERROR') details.hint = connectionHint(details);
231
236
  if (details.stage || details.submissionState) Object.assign(details, runtimeDiagnosticDetails());
232
237
  let message = FAILURE_MESSAGES[code];
238
+ if (code === 'HARNESS_RESULT_UNCERTAIN' && error?.code === 'harness-timeout' && details.stage === 'prompt.submit') {
239
+ message = PROMPT_SUBMIT_UNCONFIRMED_MESSAGE;
240
+ }
233
241
  if (['INTERNAL_UNKNOWN', 'REQUEST_TIMEOUT', 'NETWORK_ERROR'].includes(code)) {
234
242
  if (details.submissionState === 'not-submitted') {
235
243
  message = code === 'REQUEST_TIMEOUT'
@@ -439,6 +439,11 @@ function modelErrorMessage(error, action) {
439
439
 
440
440
  async function boundSession(harness, state, key, options) {
441
441
  if (typeof state?.sessionFor !== 'function') return null;
442
+ // A DS Bot binding may exist before this IM chat has received a message.
443
+ // Resolve its current part rather than creating an unrelated IM session.
444
+ if (typeof harness?.resolveDsBotSession === 'function') {
445
+ await harness.resolveDsBotSession(key);
446
+ }
442
447
  const sessionId = state.sessionFor(key);
443
448
  if (typeof sessionId !== 'string' || !sessionId) return null;
444
449
  if (typeof harness?.workspaceSession !== 'function') {
@@ -0,0 +1,7 @@
1
+ import { t } from './i18n.mjs';
2
+
3
+ export async function startNewConversation({ state, harness, key }) {
4
+ const result = await harness.prepareConversationDirectory?.(key, { explicitNew: true });
5
+ await state.clearSession(key);
6
+ return [t('已开启全新 Harness 会话。'), result?.warning ? t(result.warning) : null].filter(Boolean).join('\n');
7
+ }
@@ -0,0 +1,48 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { sameWorkspacePath } from './default-workspace.mjs';
4
+ import { validateAgentPresetId } from './agent-preset.mjs';
5
+
6
+ /** Register a preset's group without changing any bot workspace or existing session binding. */
7
+ export async function ensurePresetWorkspace(harness, workspace, preset, catalog, options = {}) {
8
+ const id = validateAgentPresetId(preset);
9
+ if (
10
+ !id ||
11
+ typeof harness?.isUngroupedWorkspace !== 'function' ||
12
+ !(await harness.isUngroupedWorkspace(workspace))
13
+ )
14
+ return workspace;
15
+ const directory = join(workspace, 'presets', id);
16
+ await mkdir(directory, { recursive: true, mode: 0o700 });
17
+ const listing = await harness.rpc('workspace.list', {}, 30000, options);
18
+ if (!Array.isArray(listing?.items)) throw new Error('Harness returned an invalid workspace list');
19
+ let existing;
20
+ for (const item of listing.items) {
21
+ if (await sameWorkspacePath(item.path, directory)) {
22
+ existing = item;
23
+ break;
24
+ }
25
+ }
26
+ // A user may rename an automatically created group. Preserve that title.
27
+ if (existing && existing.title !== id) return directory;
28
+ const result = existing
29
+ ? { workspace: existing }
30
+ : await harness.rpc('workspace.create', { path: directory }, 30000, options);
31
+ if (!result?.workspace?.workspaceId) throw new Error('Harness returned an invalid workspace');
32
+ if (result.created === false && result.workspace.title !== id) return directory;
33
+ const label = catalog?.items.find((item) => item.id === id)?.label ?? id;
34
+ const title = listing.items.some(
35
+ (item) => item.title === label && item.workspaceId !== result.workspace.workspaceId,
36
+ )
37
+ ? `${label}(${id})`
38
+ : label;
39
+ if (result.workspace.title !== title) {
40
+ await harness.rpc(
41
+ 'workspace.rename',
42
+ { workspaceId: result.workspace.workspaceId, title },
43
+ 30000,
44
+ options,
45
+ );
46
+ }
47
+ return directory;
48
+ }
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
3
- import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
3
+ import { normalizeDiagnosticDetails, safeDiagnosticMessage } from './diagnostic-details.mjs';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  let installedDependencies;
@@ -27,13 +27,19 @@ function dependencies() {
27
27
  return installedDependencies;
28
28
  }
29
29
 
30
- /** Attach only safe facts; never copy QR contents, exception text or stack traces. */
30
+ /** Attach only safe facts: no QR contents, no stack traces.
31
+ * The deepest cause's message is included when it reads as plain technical
32
+ * text (see `safeDiagnosticMessage`); it is the only fact that separates
33
+ * `QRCode.toDataURL is not a function` from a zlib failure with the same shape. */
31
34
  export function qrEncodingError(cause) {
32
35
  if (cause?.name === 'AbortError') return cause;
33
36
  const evidence = extractConnectionEvidence(cause);
37
+ const leaf = evidence.chain.at(-1);
38
+ const causeMessage = safeDiagnosticMessage(leaf?.message);
34
39
  return connectionStageError(new Error('QR encoding failed', { cause }), 'qr.encode', undefined, {
35
40
  qrEncoder: 'qrcode', qrRenderer: 'png',
36
41
  errorTypes: evidence.errors.map(error => error.type),
42
+ ...(causeMessage ? { causeMessage } : {}),
37
43
  dependencies: dependencies(),
38
44
  });
39
45
  }
@@ -1,4 +1,3 @@
1
- import { INJECTED_CONTEXT_TAGS } from '../context-enhancement.mjs';
2
1
  import { promptContentForMessage } from '../image-prompt.mjs';
3
2
 
4
3
  const REPLY_CONTENT_MAX_CODE_POINTS = 8_000;
@@ -80,7 +79,7 @@ function errorUnavailableReason(error) {
80
79
  function mergeDefined(base, loaded) {
81
80
  const merged = { ...base };
82
81
  for (const key of [
83
- 'messageId', 'authorId', 'authorName', 'content', 'attachments', 'unavailableReason',
82
+ 'messageId', 'authorId', 'authorName', 'content', 'attachments', 'files', 'unavailableReason',
84
83
  ]) {
85
84
  if (loaded[key] !== undefined) merged[key] = loaded[key];
86
85
  }
@@ -108,6 +107,7 @@ function normalizeReference(reference) {
108
107
  const authorName = cleanString(reference.authorName, REPLY_AUTHOR_NAME_MAX_CODE_POINTS);
109
108
  const content = cleanString(reference.content, REPLY_CONTENT_MAX_CODE_POINTS, { multiline: true });
110
109
  const { attachments, truncated: attachmentsTruncated } = cleanAttachments(reference.attachments);
110
+ const files = Array.isArray(reference.files) ? reference.files.filter((file) => file && typeof file.load === 'function') : [];
111
111
  let unavailableReason = cleanUnavailableReason(reference.unavailableReason);
112
112
  if (!content.value && attachments.length === 0 && !unavailableReason) {
113
113
  unavailableReason = 'not-delivered';
@@ -120,29 +120,49 @@ function normalizeReference(reference) {
120
120
  ...(authorName.value ? { authorName: authorName.value } : {}),
121
121
  ...(content.value ? { content: content.value } : {}),
122
122
  ...(attachments.length > 0 ? { attachments } : {}),
123
+ ...(files.length > 0 ? { files } : {}),
123
124
  ...(unavailableReason ? { unavailableReason } : {}),
124
125
  ...(truncated ? { truncated: true } : {}),
125
126
  };
126
127
  }
127
128
 
128
129
  function replyBlock(reference) {
129
- const json = JSON.stringify(reference).replace(/[<>&]/gu, (character) => ({
130
+ const { files: _files, ...visibleReference } = reference;
131
+ const json = JSON.stringify(visibleReference).replace(/[<>&]/gu, (character) => ({
130
132
  '<': '\\u003c',
131
133
  '>': '\\u003e',
132
134
  '&': '\\u0026',
133
135
  })[character]);
134
- return `${INJECTED_CONTEXT_TAGS.replyOpen}${json}${INJECTED_CONTEXT_TAGS.replyClose}`;
136
+ return `<dsh_im_reply_to>${json}</dsh_im_reply_to>`;
135
137
  }
136
138
 
137
139
  export function hasReplyReference(message) {
138
140
  return objectReference(message?.replyTo);
139
141
  }
140
142
 
141
- export async function promptContentForInboundMessage(message, { signal, deferImages = false } = {}) {
143
+ export async function promptContentForInboundMessage(
144
+ message,
145
+ { signal, deferImages = false, originalFiles } = {},
146
+ ) {
142
147
  if (!hasReplyReference(message)) {
143
148
  return promptContentForMessage(message, { signal, deferImages });
144
149
  }
145
150
  const reference = normalizeReference(await resolveReference(message.replyTo, signal));
151
+ // A quoted attachment is part of the user's explicit request. Preserve its
152
+ // lazy source on the current message so the normal inbound-file pipeline
153
+ // downloads and stages it alongside files attached to the new message.
154
+ if (Array.isArray(originalFiles)) {
155
+ if (!Array.isArray(message.files)) message.files = [];
156
+ // A workspace retry can rebuild the same quoted prompt. Restore the
157
+ // caller's original attachments before appending the lazy quote files;
158
+ // keep the existing array object so askOptions.files sees the update.
159
+ message.files.length = 0;
160
+ message.files.push(...originalFiles);
161
+ }
162
+ if (Array.isArray(reference.files) && reference.files.length > 0) {
163
+ if (!Array.isArray(message.files)) message.files = [];
164
+ message.files.push(...reference.files);
165
+ }
146
166
  const currentContent = await promptContentForMessage(message, { signal, deferImages });
147
167
  return [{ type: 'text', text: replyBlock(reference) }, ...currentContent];
148
168
  }
@@ -0,0 +1,159 @@
1
+ import { t } from './i18n.mjs';
2
+
3
+ /** Long enough to tell sessions apart in a chat, short enough to read. */
4
+ const SESSION_ID_DISPLAY_LENGTH = 12;
5
+
6
+ /**
7
+ * Optional /status fields must not hold the reply open when the Host is stuck.
8
+ * Three seconds is well above a healthy local RPC and short enough that the
9
+ * connection line is never buried behind a frozen Session/models read.
10
+ */
11
+ export const STATUS_FIELD_TIMEOUT_MS = 3_000;
12
+
13
+ function shortenedSessionId(sessionId) {
14
+ return sessionId.length > SESSION_ID_DISPLAY_LENGTH
15
+ ? `${sessionId.slice(0, SESSION_ID_DISPLAY_LENGTH)}…`
16
+ : sessionId;
17
+ }
18
+
19
+ /**
20
+ * The workspace the current conversation actually runs in: an explicit
21
+ * per-conversation pin when present, otherwise the bot-wide default.
22
+ */
23
+ function readWorkspace(harness, conversationKey) {
24
+ if (typeof harness?.currentConversationWorkspace === 'function'
25
+ && typeof conversationKey === 'string' && conversationKey) {
26
+ const workspace = harness.currentConversationWorkspace(conversationKey);
27
+ if (typeof workspace === 'string' && workspace) return workspace;
28
+ }
29
+ if (typeof harness?.currentWorkspace === 'function') {
30
+ const workspace = harness.currentWorkspace();
31
+ if (typeof workspace === 'string' && workspace) return workspace;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ async function readPreset(harness, options) {
37
+ if (typeof harness?.agentPresetSettings !== 'function') return null;
38
+ const settings = await harness.agentPresetSettings(options);
39
+ const preset = settings?.agentPreset;
40
+ if (typeof preset !== 'string' || !preset) return t('跟随 Host 默认');
41
+ const item = settings?.agentPresetCatalog?.items?.find((entry) => entry?.id === preset);
42
+ return item?.label ? `${item.label}(${preset})` : preset;
43
+ }
44
+
45
+ async function readModel(session, options) {
46
+ if (typeof session?.models !== 'function') return null;
47
+ const catalog = await session.models(options);
48
+ const current = catalog?.current;
49
+ if (typeof current?.provider !== 'string' || !current.provider
50
+ || typeof current?.model !== 'string' || !current.model) return null;
51
+ return `${current.provider}/${current.model}`;
52
+ }
53
+
54
+ async function readRunning(session, options) {
55
+ if (typeof session?.isRunning !== 'function') return false;
56
+ return (await session.isRunning(options)) === true;
57
+ }
58
+
59
+ /** Give the optional reads their own deadline, without cancelling the turn. */
60
+ function fieldReadOptions(signal, timeoutMs) {
61
+ const timeout = AbortSignal.timeout(timeoutMs);
62
+ return { signal: signal ? AbortSignal.any([signal, timeout]) : timeout };
63
+ }
64
+
65
+ /** A status field is optional: one failing read must not fail the command. */
66
+ async function settled(operation) {
67
+ try {
68
+ return await operation();
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * A status field is optional AND must not outlive its deadline.
76
+ *
77
+ * The abort signal alone is not enough: the real Host chain
78
+ * (`agentPresetSettings()` reads the preset directory before it re-checks the
79
+ * signal) can ignore it and never settle, which would hold the whole reply
80
+ * open. Race the read against its own timer so the deadline holds no matter
81
+ * how the underlying RPC behaves; the signal still lets cooperative readers
82
+ * cancel their work early.
83
+ */
84
+ function settledWithin(operation, timeoutMs) {
85
+ return new Promise((resolve) => {
86
+ let settledAlready = false;
87
+ const finish = (value) => {
88
+ if (settledAlready) return false;
89
+ settledAlready = true;
90
+ clearTimeout(timer);
91
+ resolve(value ?? null);
92
+ return true;
93
+ };
94
+ const timer = setTimeout(() => finish(null), timeoutMs);
95
+ timer.unref?.();
96
+ (async () => operation())().then(finish, () => finish(null));
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Render one readable /status reply for the text channels.
102
+ *
103
+ * The first line is the historical connection confirmation. Everything after
104
+ * it is best-effort: a workspace, session binding, model or Agent Preset that
105
+ * cannot be read is omitted (or explained) instead of turning the command into
106
+ * a failure. The running-task line appears only when this chat's bound session
107
+ * is actually running, so the common idle case stays short. Optional reads use
108
+ * a bounded signal ({@link STATUS_FIELD_TIMEOUT_MS}) so a frozen Host cannot
109
+ * make the command hang.
110
+ */
111
+ export async function runStatusCommand({
112
+ descriptor,
113
+ harness,
114
+ state,
115
+ conversationKey,
116
+ signal,
117
+ fieldTimeoutMs = STATUS_FIELD_TIMEOUT_MS,
118
+ } = {}) {
119
+ if (!harness || typeof harness.ensureRunning !== 'function') {
120
+ throw new TypeError('A Harness client with ensureRunning is required');
121
+ }
122
+ const options = signal ? { signal } : {};
123
+ await harness.ensureRunning(options);
124
+ const fieldTimeout = Number.isSafeInteger(fieldTimeoutMs) && fieldTimeoutMs > 0
125
+ ? fieldTimeoutMs
126
+ : STATUS_FIELD_TIMEOUT_MS;
127
+ const fieldOptions = fieldReadOptions(signal, fieldTimeout);
128
+
129
+ const label = descriptor?.label ?? 'Telegram';
130
+ const lines = [t('{label}机器人与 DeepSeek Harness 连接正常。', { label })];
131
+
132
+ const workspace = await settled(() => readWorkspace(harness, conversationKey));
133
+ if (workspace) lines.push(t('工作区:{workspace}', { workspace }));
134
+
135
+ const sessionId = await settled(async () => (typeof state?.sessionFor === 'function'
136
+ ? state.sessionFor(conversationKey)
137
+ : null));
138
+ const boundSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
139
+ lines.push(boundSessionId
140
+ ? t('绑定会话:{session}', { session: shortenedSessionId(boundSessionId) })
141
+ : t('绑定会话:未绑定(发送消息后自动创建)'));
142
+
143
+ const session = boundSessionId
144
+ ? await settled(() => (typeof harness.workspaceSession === 'function'
145
+ ? harness.workspaceSession(boundSessionId, conversationKey)
146
+ : null))
147
+ : null;
148
+ const [model, preset, running] = await Promise.all([
149
+ session ? settledWithin(() => readModel(session, fieldOptions), fieldTimeout) : null,
150
+ settledWithin(() => readPreset(harness, fieldOptions), fieldTimeout),
151
+ session ? settledWithin(() => readRunning(session, fieldOptions), fieldTimeout) : false,
152
+ ]);
153
+ if (model) lines.push(t('当前模型:{model}', { model }));
154
+ else if (!session) lines.push(t('当前模型:暂无(创建会话后显示)'));
155
+ if (preset) lines.push(t('Agent Preset(预设):{preset}', { preset }));
156
+ if (running === true) lines.push(t('运行中任务:有(发送 /stop 可停止)'));
157
+
158
+ return { message: lines.join('\n') };
159
+ }