@xmanrui/dsh-im 5.6.0 → 5.8.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 (41) hide show
  1. package/README.en.md +22 -6
  2. package/README.md +22 -6
  3. package/assets/sponsors/88api.jpg +0 -0
  4. package/lib/client.js +361 -159
  5. package/lib/index.js +323 -321
  6. package/package.json +1 -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/delivery-settings.js +13 -0
  11. package/plugin-src/client/i18n-ru.js +18 -0
  12. package/plugin-src/client/i18n.js +18 -0
  13. package/plugin-src/client/session-channel-logos.js +8 -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/feishu/rpc.mjs +25 -0
  17. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  18. package/plugin-src/host/delivery-suggestions.mjs +2 -0
  19. package/plugin-src/host/update-service.mjs +44 -13
  20. package/scripts/verify-package.mjs +17 -6
  21. package/src/channels/feishu/bridge.mjs +29 -12
  22. package/src/channels/feishu/feishu-runtime.mjs +13 -1
  23. package/src/channels/feishu/message-utils.mjs +1 -0
  24. package/src/channels/qq/markdown-reply.mjs +5 -2
  25. package/src/channels/qq/qq-bridge.mjs +41 -2
  26. package/src/channels/shared/bot-workspace-store.mjs +248 -0
  27. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  28. package/src/channels/shared/conversation-directory.mjs +29 -0
  29. package/src/channels/shared/harness-client.mjs +72 -2
  30. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  31. package/src/channels/shared/i18n-en/shared-a.mjs +5 -0
  32. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  33. package/src/channels/shared/i18n-ru/shared-a.mjs +5 -0
  34. package/src/channels/shared/message-failure.mjs +8 -0
  35. package/src/channels/shared/new-command.mjs +7 -0
  36. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  37. package/src/channels/shared/text-harness-bridge.mjs +3 -2
  38. package/src/channels/shared/workspace-command.mjs +22 -9
  39. package/src/channels/slack/slack-api.mjs +21 -5
  40. package/src/channels/slack/slack-runtime.mjs +69 -20
  41. package/src/channels/wecom/wecom-controller.mjs +89 -1
@@ -0,0 +1,46 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, realpath, stat } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { validateConversationDirectory } from './conversation-directory.mjs';
5
+
6
+ let lastSessionTimestamp = 0;
7
+
8
+ export function conversationDirectoryName(conversationKey, value, timestamp = Date.now(), identity = '') {
9
+ const config = validateConversationDirectory(value);
10
+ if (config.strategy === 'per-session') {
11
+ timestamp = Math.max(Number(timestamp) || 0, lastSessionTimestamp + 1);
12
+ lastSessionTimestamp = timestamp;
13
+ }
14
+ const digest = createHash('sha256').update(JSON.stringify([identity, conversationKey])).digest('hex').slice(0, 16);
15
+ const suffix = `-${digest}${config.strategy === 'per-session' ? `-${timestamp}` : ''}`;
16
+ const readable = conversationKey.replace(/[<>:"/\\|?*\u0000-\u001f\u007f]/gu, '-');
17
+ const room = Math.max(0, 100 - config.prefix.length - suffix.length);
18
+ return `${config.prefix}${readable.slice(0, room)}${suffix}`;
19
+ }
20
+
21
+ export async function prepareDirectoryPath(base, directory) {
22
+ const root = await realpath(resolve(base));
23
+ const target = resolve(directory);
24
+ if (dirname(target) !== root) throw new Error('会话目录必须直接位于基工作区下。');
25
+ try {
26
+ const info = await stat(target);
27
+ if (!info.isDirectory()) throw new Error('会话目录路径不是目录。');
28
+ if ((await realpath(target)) !== target) throw new Error('会话目录不能是符号链接。');
29
+ } catch (error) {
30
+ if (error.code !== 'ENOENT') throw error;
31
+ await mkdir(target, { recursive: false, mode: 0o700 });
32
+ }
33
+ return target;
34
+ }
35
+
36
+ export async function ensureConversationDirectory({ baseWorkspace, conversationKey, config, sessionTimestamp }) {
37
+ const normalized = validateConversationDirectory(config);
38
+ const directory = resolve(baseWorkspace, conversationDirectoryName(conversationKey, normalized, sessionTimestamp));
39
+ try {
40
+ await prepareDirectoryPath(baseWorkspace, directory);
41
+ return { workspace: directory };
42
+ } catch (error) {
43
+ console.warn('[dsh-im] conversation directory preparation failed:', error?.message ?? error);
44
+ return { warning: '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。' };
45
+ }
46
+ }
@@ -0,0 +1,29 @@
1
+ export const DEFAULT_CONVERSATION_DIRECTORY = Object.freeze({
2
+ enabled: false,
3
+ strategy: 'per-conversation',
4
+ prefix: 'conv-',
5
+ });
6
+
7
+ export function validateConversationDirectory(value) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value)
9
+ || Object.keys(value).some((key) => !['enabled', 'strategy', 'prefix'].includes(key))
10
+ || typeof value.enabled !== 'boolean'
11
+ || (value.strategy !== undefined && !['per-conversation', 'per-session'].includes(value.strategy))
12
+ || (value.prefix !== undefined && (typeof value.prefix !== 'string' || !/^[A-Za-z0-9_-]{1,32}$/.test(value.prefix)))) {
13
+ const error = new Error('会话目录设置无效:前缀须为 1–32 位字母、数字、下划线或连字符。');
14
+ error.code = 'conversation-directory-invalid';
15
+ throw error;
16
+ }
17
+ return { ...DEFAULT_CONVERSATION_DIRECTORY, ...value };
18
+ }
19
+
20
+ export function normalizeConversationDirectory(value) {
21
+ if (value === null || value === undefined) return null;
22
+ try { return validateConversationDirectory(value); } catch { return null; }
23
+ }
24
+
25
+ export function workspaceManualEditDisabled() {
26
+ const error = new Error('会话目录隔离已开启,无法手动修改工作区。');
27
+ error.code = 'workspace-manual-edit-disabled';
28
+ return error;
29
+ }
@@ -891,6 +891,16 @@ export class HarnessTransportError extends Error {
891
891
  }
892
892
  }
893
893
 
894
+ /**
895
+ * session.prompt 提交超时(30 秒窗口到期)只说明应答迟到,不代表提交失败:
896
+ * 单进程 Host 忙碌时 prompt 往往已入队。这类错误需要先回查持久账本再定性。
897
+ */
898
+ function isPromptSubmitTimeout(error) {
899
+ return error instanceof HarnessTransportError
900
+ && error.code === 'harness-timeout'
901
+ && error.method === 'session.prompt';
902
+ }
903
+
894
904
  export class HarnessHealthError extends Error {
895
905
  constructor(cause) {
896
906
  super('Harness health RPC was rejected', { cause });
@@ -1434,6 +1444,46 @@ export class HarnessClient {
1434
1444
  }
1435
1445
  }
1436
1446
 
1447
+ /**
1448
+ * 提交超时后的入库确认:session.history 是持久账本,按 promptRpcId 找回我们的
1449
+ * 持久化痕迹(已执行的 user/message,或已入队待执行的 agent/inbox/spliced
1450
+ * 回执)即视为提交已成功,让 ask() 继续等回复而不是误报失败。
1451
+ * 确认探测自身的失败一律吞掉——它们不能掩盖或改变原始提交超时的定性;
1452
+ * 唯独取消例外:取消原因必须优先于超时透出。
1453
+ */
1454
+ async #confirmPromptSubmit(sessionId, promptRpcId, { signal } = {}) {
1455
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1456
+ if (signal?.aborted) return false;
1457
+ try {
1458
+ const history = await this.#sessionRpc('session.history', {
1459
+ sessionId,
1460
+ maxMessages: 50,
1461
+ }, 30_000, { signal });
1462
+ const confirmed = (history?.events ?? []).some((entry) => {
1463
+ const event = entry?.event ?? entry;
1464
+ if (event?.type === 'user/message') {
1465
+ return event?.data?.source?.rpcId === promptRpcId;
1466
+ }
1467
+ // queue 模式下消息可能已持久入队但尚未产生 user/message:
1468
+ // agent/inbox/spliced 的 inserted[].source.rpcId 就是入队回执。
1469
+ if (event?.type === 'agent/inbox/spliced') {
1470
+ return (event?.data?.inserted ?? [])
1471
+ .some((message) => message?.source?.rpcId === promptRpcId);
1472
+ }
1473
+ return false;
1474
+ });
1475
+ if (confirmed) return true;
1476
+ } catch (probeError) {
1477
+ // 取消优先于超时定性:最后一次探测期间被取消时,循环后面没有
1478
+ // sleep 再检查 abort,必须在这里把取消原因抛出,不能被超时覆盖。
1479
+ if (signal?.aborted) throw signal.reason ?? probeError;
1480
+ // 其余账本探测失败不改变定性:本轮未确认,继续轮询或最终按原超时上报。
1481
+ }
1482
+ if (attempt < 4) await sleep(2_000, signal);
1483
+ }
1484
+ return false;
1485
+ }
1486
+
1437
1487
  async sessionExists(sessionId, options = {}) {
1438
1488
  // Archived Sessions still exist. Returning false here would silently bind
1439
1489
  // the conversation to a new Session; reading their active log can also fail.
@@ -2037,8 +2087,28 @@ export class HarnessClient {
2037
2087
  ...timeZoneFields,
2038
2088
  }, 30_000, { rpcId: promptRpcId, signal });
2039
2089
  };
2090
+ // 30 秒提交窗口到期只说明 Host 忙到没来得及应答,prompt 可能早已入队。
2091
+ // 先按 promptRpcId 回查持久账本,确认入库就继续等回复;确认不到才把
2092
+ // 原始超时错误向上抛,由文案层标注「提交请求超时、是否送达未知」。
2093
+ const submitPrompt = async (promptContent) => {
2094
+ try {
2095
+ await sendPrompt(promptContent);
2096
+ } catch (error) {
2097
+ if (!isPromptSubmitTimeout(error) || signal?.aborted) throw error;
2098
+ let confirmed = false;
2099
+ try {
2100
+ confirmed = await this.#confirmPromptSubmit(sessionId, promptRpcId, { signal });
2101
+ } catch (confirmError) {
2102
+ // 确认途中被取消时恢复调用方的取消语义(与图片暂存路径一致)。
2103
+ if (signal?.aborted) throw signal.reason ?? confirmError;
2104
+ throw error;
2105
+ }
2106
+ if (!confirmed) throw error;
2107
+ diagnostic.submissionState = 'accepted';
2108
+ }
2109
+ };
2040
2110
  try {
2041
- await sendPrompt(content);
2111
+ await submitPrompt(content);
2042
2112
  } catch (error) {
2043
2113
  // The Host refuses image blocks for a non-vision model before any
2044
2114
  // durable user message exists. Re-deliver the same bytes the way
@@ -2073,7 +2143,7 @@ export class HarnessClient {
2073
2143
  ...contentWithoutImages(baseContent),
2074
2144
  { type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
2075
2145
  ], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
2076
- await sendPrompt(fallbackPrompt);
2146
+ await submitPrompt(fallbackPrompt);
2077
2147
  }
2078
2148
  promptAccepted = true;
2079
2149
  diagnostic.submissionState = 'accepted';
@@ -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",
@@ -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.',
@@ -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
  '代理已配置': 'Прокси настроен',
@@ -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
  '任务已完成。': 'Задача выполнена.',
@@ -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'
@@ -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
+ }
@@ -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
  }
@@ -75,6 +75,7 @@ import {
75
75
  } from './message-failure.mjs';
76
76
  import { logDeliveryFailure } from './delivery-failure-log.mjs';
77
77
  import { beginStatusReaction } from './status-reaction.mjs';
78
+ import { startNewConversation } from './new-command.mjs';
78
79
 
79
80
  /** Cap and TTL for the in-memory workspace-picker snapshots behind button presses. */
80
81
  const MAX_WORKSPACE_CARDS = 50;
@@ -1141,7 +1142,7 @@ export class TextHarnessBridge {
1141
1142
  return;
1142
1143
  }
1143
1144
  if (!hasImages && !hasFiles && command === '/new') {
1144
- await this.#state.clearSession(conversationKey);
1145
+ const receipt = await startNewConversation({ state: this.#state, harness: this.#harness, key: conversationKey });
1145
1146
  if (this.#contextHooks?.onSessionCleared) {
1146
1147
  try {
1147
1148
  await this.#contextHooks.onSessionCleared(conversationKey);
@@ -1150,7 +1151,7 @@ export class TextHarnessBridge {
1150
1151
  this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] failed to reset context anchors after /new:`, error?.message ?? error);
1151
1152
  }
1152
1153
  }
1153
- await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
1154
+ await this.#bot.sendText(target, `${receipt}\n${t('请发送你的问题。')}`);
1154
1155
  return;
1155
1156
  }
1156
1157
  const compactCommand = !hasImages && !hasFiles
@@ -112,18 +112,23 @@ async function selectedWorkspacePath(value) {
112
112
  }
113
113
  }
114
114
 
115
- export async function workspacePathSnapshot(harness, { includeTitles = false, ...options } = {}) {
115
+ export async function workspacePathSnapshot(harness, { includeTitles = false, includeConversationDirectories = false, conversationKey, ...options } = {}) {
116
116
  const withEntries = includeTitles && typeof harness.listWorkspaceEntries === 'function';
117
117
  const listed = await (withEntries ? harness.listWorkspaceEntries(options) : harness.listWorkspaces(options));
118
- const currentValue = typeof harness?.currentWorkspace === 'function'
119
- ? harness.currentWorkspace()
120
- : null;
118
+ const currentValue = typeof harness?.currentConversationWorkspace === 'function'
119
+ && typeof conversationKey === 'string' && conversationKey
120
+ ? harness.currentConversationWorkspace(conversationKey)
121
+ : typeof harness?.currentWorkspace === 'function'
122
+ ? harness.currentWorkspace()
123
+ : null;
121
124
  const current = await existingWorkspacePath(currentValue);
122
125
  const entries = await Promise.all((Array.isArray(listed) ? listed : []).map(async (item) => ({
123
126
  path: await existingWorkspacePath(withEntries ? item?.path : item),
124
127
  title: withEntries ? safeDisplayText(item?.title) : '',
125
128
  })));
126
- const paths = [...new Set([...(current ? [current] : []), ...entries.map((item) => item.path).filter(Boolean)])];
129
+ const directoryPaths = new Set(harness.conversationDirectoryPaths?.() ?? []);
130
+ const paths = [...new Set([...(current ? [current] : []), ...entries.map((item) => item.path).filter(Boolean)])]
131
+ .filter((path) => includeConversationDirectories || path === current || !directoryPaths.has(path));
127
132
  const titles = {};
128
133
  if (includeTitles) {
129
134
  for (const item of entries) {
@@ -162,12 +167,14 @@ export function splitWorkspaceCommandMessage(message) {
162
167
  * channel without an interactive picker keeps exactly what it always showed;
163
168
  * `listing` is the machine-readable half a channel may render as a picker.
164
169
  */
165
- async function workspaceListingCommand(harness) {
170
+ async function workspaceListingCommand(harness, { includeConversationDirectories = false } = {}) {
166
171
  if (typeof harness?.listWorkspaces !== 'function') {
167
172
  return commandResult(t('当前机器人暂不支持列出工作区。'));
168
173
  }
169
174
  try {
170
- const { current, paths, titles } = await workspacePathSnapshot(harness, { includeTitles: true });
175
+ const { current, paths, titles } = await workspacePathSnapshot(harness, {
176
+ includeTitles: true, includeConversationDirectories,
177
+ });
171
178
  if (paths.length === 0) {
172
179
  return commandResult(t('当前 Harness Host 上没有仍然存在的已登记工作区。'));
173
180
  }
@@ -195,8 +202,9 @@ async function workspaceListingCommand(harness) {
195
202
  }
196
203
 
197
204
  async function runWorkspaceListCommand(match, harness) {
198
- if (match[1]?.trim()) return commandResult(t('用法:/workspacelist'));
199
- return workspaceListingCommand(harness);
205
+ const includeConversationDirectories = match[1]?.trim().toLowerCase() === 'all';
206
+ if (match[1]?.trim() && !includeConversationDirectories) return commandResult(t('用法:/workspacelist'));
207
+ return workspaceListingCommand(harness, { includeConversationDirectories });
200
208
  }
201
209
 
202
210
  async function conversationEffectiveWorkspace(harness, conversationKey) {
@@ -475,6 +483,7 @@ async function runConversationWorkspaceCommand(command, harness, conversationKey
475
483
  try {
476
484
  let selected = argument;
477
485
  if (/^\d+$/u.test(argument)) {
486
+ // Match the ordering shown by /workspacelist, /ws and bare /conv.
478
487
  const { paths } = await workspacePathSnapshot(harness);
479
488
  const position = Number(argument);
480
489
  if (!Number.isSafeInteger(position) || position < 1 || position > paths.length) {
@@ -516,6 +525,10 @@ export function workspaceSwitchFailureText(error) {
516
525
 
517
526
  export async function runWorkspaceCommand(text, harness, conversationKey) {
518
527
  if (!isWorkspaceCommand(text)) return null;
528
+ const config = harness.conversationDirectoryConfig?.();
529
+ if (config?.enabled === true && /^(?:\/(?:workspace|ws|conv|conversation|thread))(?:\s|$)/iu.test(text.trim())) {
530
+ return { message: '', messages: [] };
531
+ }
519
532
  const command = text.trim();
520
533
  const threadMatch = THREAD_WORKSPACE_COMMAND.exec(command);
521
534
  if (threadMatch) {
@@ -155,6 +155,8 @@ function requiredString(value, name) {
155
155
  return result;
156
156
  }
157
157
 
158
+ const SLACK_MARKDOWN_TEXT_LIMIT = 12_000;
159
+
158
160
  function safeOutgoingText(value, { trim = true } = {}) {
159
161
  const raw = typeof value === 'string' ? value : '';
160
162
  const text = trim ? raw.trim() : raw;
@@ -164,6 +166,14 @@ function safeOutgoingText(value, { trim = true } = {}) {
164
166
  .replace(/<!(channel|here|everyone)(?:\^[^>]*)?>/gi, '@$1');
165
167
  }
166
168
 
169
+ function markdownTextField(value) {
170
+ const text = safeOutgoingText(value);
171
+ if (text.length > SLACK_MARKDOWN_TEXT_LIMIT) {
172
+ throw new TypeError(`Slack markdown_text exceeds ${SLACK_MARKDOWN_TEXT_LIMIT} characters`);
173
+ }
174
+ return text;
175
+ }
176
+
167
177
  function apiFailure(method, payload, tokenKind) {
168
178
  const reason = cleanString(payload?.error) ?? 'unknown_error';
169
179
  const error = new Error(`Slack ${method} failed: ${reason.replaceAll('_', ' ')}`);
@@ -272,15 +282,22 @@ export class SlackApi {
272
282
  }
273
283
 
274
284
  postMessage({ channelId, text, threadTs, signal, format = 'plain' }) {
285
+ const outgoing = format === 'markdown_text' ? markdownTextField(text) : safeOutgoingText(text);
286
+ const markdownText = format === 'markdown_text';
275
287
  return this.#request('chat.postMessage', {
276
288
  tokenKind: 'bot',
277
289
  signal,
278
290
  body: {
279
291
  channel: slackId(channelId, 'channel id'),
280
- text: safeOutgoingText(text),
281
- ...(format === 'markdown' ? { blocks: [{ type: 'markdown', text: safeOutgoingText(text) }] } : {}),
292
+ // markdown_text cannot be combined with text or blocks.
293
+ ...(markdownText
294
+ ? { markdown_text: outgoing }
295
+ : {
296
+ text: outgoing,
297
+ ...(format === 'markdown' ? { blocks: [{ type: 'markdown', text: outgoing }] } : {}),
298
+ mrkdwn: format !== 'literal',
299
+ }),
282
300
  ...(threadTs ? { thread_ts: cleanString(threadTs) } : {}),
283
- mrkdwn: true,
284
301
  link_names: false,
285
302
  unfurl_links: false,
286
303
  unfurl_media: false,
@@ -295,8 +312,7 @@ export class SlackApi {
295
312
  body: {
296
313
  channel: slackId(channelId, 'channel id'),
297
314
  ts: requiredString(ts, 'message timestamp'),
298
- text: safeOutgoingText(text),
299
- parse: 'none',
315
+ markdown_text: markdownTextField(text),
300
316
  link_names: false,
301
317
  },
302
318
  });
@@ -10,6 +10,8 @@ import { createSlackBridgeStatus, SlackHarnessBridge } from './slack-bridge.mjs'
10
10
  const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
11
11
  const SLACK_MESSAGE_LIMIT = 38_000;
12
12
  const SLACK_STREAM_CHUNK_LIMIT = 11_000;
13
+ const SLACK_MARKDOWN_BLOCK_REJECTION = Object.freeze(['invalid_blocks', 'invalid_blocks_format']);
14
+ const SLACK_MARKDOWN_REJECTION = Object.freeze([...SLACK_MARKDOWN_BLOCK_REJECTION, 'invalid_markdown']);
13
15
  const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
14
16
 
15
17
  function addSocketListener(socket, event, listener) {
@@ -304,18 +306,40 @@ async function createSlackMessageStream({ api, target, signal, logger }) {
304
306
  if (!broken && first.startsWith(appended)) {
305
307
  await appendInChunks(api, target, ts, first.slice(appended.length), signal);
306
308
  await api.stopStream({ channelId: target.channelId, ts, signal });
309
+ for (const chunk of chunks.slice(1)) {
310
+ const result = await api.postMessage({
311
+ channelId: target.channelId,
312
+ threadTs: target.threadTs,
313
+ text: chunk,
314
+ signal,
315
+ });
316
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
317
+ }
307
318
  } else {
319
+ const reason = broken ? 'broken' : 'prefix-mismatch';
308
320
  await api.stopStream({ channelId: target.channelId, ts, signal }).catch(() => undefined);
309
- await api.updateMessage({ channelId: target.channelId, ts, text: first, signal });
310
- }
311
- for (const chunk of chunks.slice(1)) {
312
- const result = await api.postMessage({
321
+ const source = typeof text === 'string' && text.trim() ? text.trim() : t('处理完成。');
322
+ const parts = chunkMarkdownParts(source, SLACK_STREAM_CHUNK_LIMIT);
323
+ const markdownParts = parts.length > 0 ? parts : [{ markdown: source }];
324
+ logger?.warn?.(
325
+ `[dsh-im:slack] stream finalize fell back to chat.update (${reason}, length ${markdownParts[0].markdown.length})`,
326
+ );
327
+ await api.updateMessage({
313
328
  channelId: target.channelId,
314
- threadTs: target.threadTs,
315
- text: chunk,
329
+ ts,
330
+ text: markdownParts[0].markdown,
316
331
  signal,
317
332
  });
318
- if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
333
+ for (const chunk of markdownParts.slice(1)) {
334
+ const result = await api.postMessage({
335
+ channelId: target.channelId,
336
+ threadTs: target.threadTs,
337
+ text: chunk.markdown,
338
+ format: 'markdown_text',
339
+ signal,
340
+ });
341
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
342
+ }
319
343
  }
320
344
  },
321
345
  cancel() {
@@ -339,6 +363,41 @@ export class SlackBotClient {
339
363
  this.#logger = logger;
340
364
  }
341
365
 
366
+ #postMarkdown(target, text, format) {
367
+ return this.#api.postMessage({
368
+ channelId: target.channelId,
369
+ threadTs: target.threadTs,
370
+ text,
371
+ format,
372
+ signal: this.#signal,
373
+ });
374
+ }
375
+
376
+ async #recoverRejectedMarkdown(target, chunk, error) {
377
+ // Retry only a definite formatting rejection, never an ambiguous send.
378
+ if (this.#signal?.aborted || Number(error?.status) >= 500
379
+ || !SLACK_MARKDOWN_REJECTION.includes(error?.providerCode)) throw error;
380
+ if (SLACK_MARKDOWN_BLOCK_REJECTION.includes(error.providerCode)) {
381
+ this.#logger?.warn?.(
382
+ `[dsh-im:slack] Markdown block rejected (${error.providerCode}); retrying markdown_text, length ${chunk.markdown.length}`,
383
+ );
384
+ try {
385
+ const result = await this.#postMarkdown(target, chunk.markdown, 'markdown_text');
386
+ return typeof result?.ts === 'string' && result.ts ? [result.ts] : [];
387
+ } catch (retryError) {
388
+ if (this.#signal?.aborted || Number(retryError?.status) >= 500
389
+ || retryError?.providerCode !== 'invalid_markdown') throw retryError;
390
+ error = retryError;
391
+ }
392
+ }
393
+ this.#logger?.warn?.(
394
+ `[dsh-im:slack] Markdown rejected (${error.providerCode}); sending this chunk as literal text, length ${chunk.plain?.length ?? 0}`,
395
+ );
396
+ if (!chunk.plain) return [];
397
+ const result = await this.#postMarkdown(target, chunk.plain, 'literal');
398
+ return typeof result?.ts === 'string' && result.ts ? [result.ts] : [];
399
+ }
400
+
342
401
  async sendText(target, text) {
343
402
  const chunks = splitMessageText(text, SLACK_MESSAGE_LIMIT);
344
403
  const providerMessageIds = [];
@@ -362,21 +421,11 @@ export class SlackBotClient {
362
421
  for (const chunk of chunkMarkdownParts(block.text, SLACK_STREAM_CHUNK_LIMIT)) {
363
422
  this.#signal?.throwIfAborted();
364
423
  try {
365
- const result = await this.#api.postMessage({
366
- channelId: target.channelId, threadTs: target.threadTs,
367
- text: chunk.markdown, format: 'markdown', signal: this.#signal,
368
- });
424
+ const result = await this.#postMarkdown(target, chunk.markdown, 'markdown');
369
425
  if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
370
426
  } catch (error) {
371
- // Retry only a definite formatting rejection, never an ambiguous send.
372
- if (this.#signal?.aborted || Number(error?.status) >= 500
373
- || !['invalid_blocks', 'invalid_blocks_format', 'invalid_markdown']
374
- .includes(error?.providerCode)) throw error;
375
- this.#logger?.warn?.('[dsh-im:slack] Markdown rejected; sending this chunk as text');
376
- if (chunk.plain) {
377
- const result = await this.sendText(target, chunk.plain);
378
- providerMessageIds.push(...result.providerMessageIds);
379
- }
427
+ const delivered = await this.#recoverRejectedMarkdown(target, chunk, error);
428
+ providerMessageIds.push(...delivered);
380
429
  }
381
430
  }
382
431
  return { providerMessageIds };