@xmanrui/dsh-im 5.5.0 → 5.6.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 (50) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/lib/client.js +309 -243
  4. package/lib/index.js +307 -307
  5. package/package.json +4 -4
  6. package/plugin-src/client/channels/dingtalk/index.js +12 -9
  7. package/plugin-src/client/channels/feishu/group-settings.js +5 -5
  8. package/plugin-src/client/channels/feishu/index.js +33 -25
  9. package/plugin-src/client/channels/qq/index.js +5 -5
  10. package/plugin-src/client/channels/shared/token-api.js +12 -7
  11. package/plugin-src/client/channels/shared/token-channel.js +18 -11
  12. package/plugin-src/client/channels/wecom/index.js +5 -5
  13. package/plugin-src/client/channels/wecom-app/index.js +3 -3
  14. package/plugin-src/client/channels/weixin/index.js +2 -2
  15. package/plugin-src/client/channels/whatsapp/index.js +6 -6
  16. package/plugin-src/client/credential-binding.js +3 -2
  17. package/plugin-src/client/delivery-settings.js +3 -3
  18. package/plugin-src/client/ds-bot-settings.js +3 -3
  19. package/plugin-src/client/global-settings.js +5 -2
  20. package/plugin-src/client/i18n-ru.js +56 -34
  21. package/plugin-src/client/i18n.js +210 -124
  22. package/scripts/verify-package.mjs +1 -1
  23. package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
  24. package/src/channels/feishu/bridge.mjs +25 -3
  25. package/src/channels/feishu/feishu-cards.mjs +1 -45
  26. package/src/channels/feishu/slash-command-panel.mjs +2 -5
  27. package/src/channels/qq/qq-bridge.mjs +1 -0
  28. package/src/channels/shared/bot-workspace-store.mjs +1 -1
  29. package/src/channels/shared/command-catalog.mjs +8 -5
  30. package/src/channels/shared/delivery-failure-log.mjs +111 -0
  31. package/src/channels/shared/diagnostic-details.mjs +1 -0
  32. package/src/channels/shared/harness-client.mjs +12 -6
  33. package/src/channels/shared/i18n-en/shared-b.mjs +5 -0
  34. package/src/channels/shared/i18n-en/shared-c.mjs +3 -0
  35. package/src/channels/shared/i18n-en/telegram.mjs +6 -0
  36. package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
  37. package/src/channels/shared/i18n-ru/shared-c.mjs +3 -0
  38. package/src/channels/shared/i18n-ru/telegram.mjs +5 -0
  39. package/src/channels/shared/message-failure.mjs +5 -2
  40. package/src/channels/shared/session-error.mjs +8 -0
  41. package/src/channels/shared/text-harness-bridge.mjs +201 -3
  42. package/src/channels/shared/workspace-command.mjs +41 -16
  43. package/src/channels/shared/workspace-labels.mjs +65 -0
  44. package/src/channels/shared/workspace-session.mjs +24 -4
  45. package/src/channels/telegram/telegram-api.mjs +31 -2
  46. package/src/channels/telegram/telegram-bridge.mjs +58 -0
  47. package/src/channels/telegram/telegram-runtime.mjs +85 -3
  48. package/src/channels/wecom/wecom-bridge.mjs +1 -0
  49. package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
  50. package/src/channels/weixin/weixin-bridge.mjs +1 -0
@@ -32,16 +32,13 @@ export const SLASH_COMMAND_MANIFEST = Object.freeze([
32
32
  { command: 'compact', icon: 'ai-block_outlined', default: '压缩当前会话上下文', en_us: 'Compact the current session' },
33
33
  { command: 'clear', icon: 'clear_outlined', default: '清空当前会话上下文', en_us: 'Clear the current session context' },
34
34
  { command: 'sessionlist', icon: 'chat-ai_outlined', default: '列出会话', en_us: 'List sessions' },
35
- { command: 'workspacelist', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
36
- { command: 'workspaces', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
37
- { command: 'wsl', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
38
- { command: 'ws', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' },
35
+ { command: 'ws', icon: 'folder_outlined', default: '查看并切换工作区', en_us: 'View and switch workspace' },
39
36
  { command: 'watch', icon: 'flag_outlined', default: '关注一个会话', en_us: 'Watch a session' },
40
37
  { command: 'unwatch', icon: 'clear_outlined', default: '取消关注会话', en_us: 'Unwatch a session' },
41
38
  { command: 'watchlist', icon: 'flag_outlined', default: '查看关注列表', en_us: 'List watched sessions' },
42
39
  { command: 'archived', icon: 'folder_outlined', default: '设置归档会话显隐(on/off)', en_us: 'Show or hide archived sessions (on/off)' },
43
40
  { command: 'history', icon: 'chat-ai_outlined', default: '查看最近历史消息(仅私聊)', en_us: 'Show recent history (private chats only)' },
44
- { command: 'workspace', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' },
41
+ { command: 'workspace', icon: 'folder_outlined', default: '查看并切换工作区', en_us: 'View and switch workspace' },
45
42
  { command: 'conv', icon: 'folder_outlined', default: '设置当前对话专属工作区', en_us: 'Set the workspace for this conversation' },
46
43
  { command: 'session', icon: 'chat-ai_outlined', default: '绑定已有会话', en_us: 'Bind an existing session' },
47
44
  { command: 'models', icon: 'ai-functions_outlined', default: '列出可用模型', en_us: 'List available models' },
@@ -1272,6 +1272,7 @@ export class QqHarnessBridge {
1272
1272
  // already own.
1273
1273
  await this.#markPendingSubmitted(key, messageId);
1274
1274
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
1275
+ onNotice: (notice) => this.#bot.sendText(target, notice),
1275
1276
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1276
1277
  harness: this.#harness,
1277
1278
  state: this.#state,
@@ -1651,7 +1651,7 @@ export function createBotWorkspaceScope(
1651
1651
  const dsBinding = (key) => workspaces.dsBotBindingFor?.(botId, key);
1652
1652
  const assertNoDsBinding = (key) => {
1653
1653
  if (dsBinding(key)) {
1654
- throw deliveryTargetError('ds-bot-bound', '请先在“绑定bot”中解除绑定,再切换会话或工作目录。');
1654
+ throw deliveryTargetError('ds-bot-bound', t('请先在“绑定 DS Bot”中解除绑定,再切换会话或工作目录。'));
1655
1655
  }
1656
1656
  };
1657
1657
  const presetSettings = async (catalog = agentPresetCatalog) => {
@@ -35,18 +35,21 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
35
35
  defineCatalogCommand('history', '查看最近历史消息(仅私聊)', [
36
36
  '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)',
37
37
  ], { privateOnly: true }),
38
- defineCatalogCommand('workspace', '切换工作区', [
38
+ // Merged listing+switch command: no argument opens the picker, an argument
39
+ // switches directly. /wsl and friends stay accepted but leave the menu so
40
+ // there is one workspace entry to choose from.
41
+ defineCatalogCommand('workspace', '查看或切换工作区', [
42
+ '/workspace 或 /ws 查看可切换的工作区(点按钮切换)',
39
43
  '/workspace 工作区序号或绝对路径 切换工作区',
40
- ], { aliases: ['ws'] }),
44
+ ], { aliases: [{ name: 'ws', menuVisible: false }] }),
41
45
  defineCatalogCommand('conv', '设置当前对话专属工作区', [
42
46
  '/conv 或 /conversation 查看当前对话工作区',
43
47
  '/conv 工作区绝对路径或序号 设置当前对话专属工作区',
44
48
  '/conv clear 清除专属工作区,回到 bot 默认工作区',
45
49
  ], { aliases: ['conversation', 'thread'] }),
46
50
  defineCatalogCommand('workspacelist', '列出工作区绝对路径', [
47
- '/workspacelist 列出工作区绝对路径',
48
- '/ws、/wsl、/workspaces 工作区命令别名',
49
- ], { aliases: ['workspaces', 'wsl'] }),
51
+ '/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)',
52
+ ], { aliases: ['workspaces', 'wsl'], menuVisible: false }),
50
53
  defineCatalogCommand('sessionlist', '列出会话 ID 和标题', [
51
54
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
52
55
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
@@ -0,0 +1,111 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ /**
4
+ * One structured log line per failed or unconfirmed delivery.
5
+ *
6
+ * The reference id in the notice a user sees (`MF-…`) used to live only on
7
+ * screen: when a real `CHANNEL_DELIVERY_UNCERTAIN` notice appeared, nothing in
8
+ * the log explained it, so the id the user quoted back could not be traced.
9
+ * This module writes the same id, the attempt history and the full text of the
10
+ * part that failed into the local log, so the next occurrence is diagnosable.
11
+ *
12
+ * The line is a single string on purpose: a logger that pretty-prints an object
13
+ * would break it across many lines and make it impossible to grep by id.
14
+ */
15
+
16
+ /** `MF-` plus eight characters of a UUID: the id a user can quote back. */
17
+ export function createFailureReferenceId() {
18
+ return `MF-${randomUUID().slice(0, 8).toUpperCase()}`;
19
+ }
20
+
21
+ // A bot token looks like `1234:AA…` and must never reach a log line. Only
22
+ // platform descriptions pass through the scrubber; message text is logged
23
+ // verbatim because "what could not be sent" is the whole point of the record.
24
+ const TOKEN_SHAPE = /bot\d+:[A-Za-z0-9_-]{20,}/gu;
25
+
26
+ function safeText(value) {
27
+ return typeof value === 'string' && value ? value.replace(TOKEN_SHAPE, 'bot<redacted>') : null;
28
+ }
29
+
30
+ function attemptRecord(value) {
31
+ if (!value || typeof value !== 'object') return null;
32
+ const status = Number(value.status);
33
+ const retryAfter = Number(value.retry_after ?? value.retryAfter);
34
+ const attempt = Number(value.attempt);
35
+ return {
36
+ attempt: Number.isInteger(attempt) ? attempt : null,
37
+ method: typeof value.method === 'string' && value.method ? value.method : null,
38
+ status: Number.isInteger(status) ? status : null,
39
+ description: safeText(value.description ?? value.message),
40
+ retry_after: Number.isFinite(retryAfter) ? retryAfter : null,
41
+ };
42
+ }
43
+
44
+ function partRecord(value) {
45
+ if (!value || typeof value !== 'object') return null;
46
+ const index = Number(value.index);
47
+ const text = typeof value.text === 'string' ? value.text : null;
48
+ const length = Number(value.length);
49
+ const messageId = value.message_id ?? value.messageId ?? null;
50
+ return {
51
+ index: Number.isInteger(index) ? index : null,
52
+ length: Number.isInteger(length) ? length : (text?.length ?? 0),
53
+ message_id: messageId === null || messageId === undefined ? null : String(messageId),
54
+ // The text is kept for parts the platform never confirmed: those are the
55
+ // ones nobody can find in the chat afterwards.
56
+ ...(text ? { text } : {}),
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Build the log line for one failure object that carries a `referenceId`.
62
+ *
63
+ * `evidence` is what the channel could observe about the send itself (attempt
64
+ * history, per-part message ids, chat topic, markup mode). Channels without it
65
+ * still get a line, just a shorter one.
66
+ */
67
+ export function deliveryFailureLogLine(channelKey, failure, evidence = null) {
68
+ const detail = evidence && typeof evidence === 'object' ? evidence : {};
69
+ const attempts = (Array.isArray(detail.attempts) ? detail.attempts : [])
70
+ .map(attemptRecord)
71
+ .filter(Boolean);
72
+ const parts = (Array.isArray(detail.parts) ? detail.parts : [])
73
+ .map(partRecord)
74
+ .filter(Boolean);
75
+ const failedPart = Number(detail.failed_part ?? detail.failedPart);
76
+ const record = {
77
+ referenceId: failure?.referenceId ?? null,
78
+ code: failure?.code ?? null,
79
+ reason: failure?.reason ?? null,
80
+ provider_reason: safeText(detail.provider_reason ?? detail.reason),
81
+ deliveryOutcome: detail.deliveryOutcome ?? failure?.deliveryOutcome ?? null,
82
+ attempt_count: attempts.length,
83
+ attempts,
84
+ chat_id: detail.chat_id === undefined || detail.chat_id === null ? null : String(detail.chat_id),
85
+ message_thread_id: Number.isInteger(detail.message_thread_id) ? detail.message_thread_id : null,
86
+ parse_mode: detail.parse_mode ?? null,
87
+ failed_part: Number.isInteger(failedPart) ? failedPart : null,
88
+ parts,
89
+ };
90
+ return `[dsh-im:${channelKey}] delivery failed [${failure?.referenceId ?? 'unknown'}]: `
91
+ + JSON.stringify(record);
92
+ }
93
+
94
+ /** Failure codes that describe a send, not something that happened before it. */
95
+ const DELIVERY_FAILURE_CODES = new Set([
96
+ 'CHANNEL_DELIVERY',
97
+ 'CHANNEL_DELIVERY_UNCERTAIN',
98
+ 'CHANNEL_PERMISSION',
99
+ 'CHANNEL_RATE_LIMIT',
100
+ ]);
101
+
102
+ /** Emit the line through whatever logger the channel was given. */
103
+ export function logDeliveryFailure(logger, channelKey, failure, evidence = null) {
104
+ if (!failure?.referenceId) return null;
105
+ // Other failures already log their own diagnostics; this line exists for the
106
+ // notices whose reference id would otherwise never reach the log.
107
+ if (!evidence && !DELIVERY_FAILURE_CODES.has(failure.code)) return null;
108
+ const line = deliveryFailureLogLine(channelKey, failure, evidence);
109
+ (logger?.error ?? logger?.warn)?.call(logger, line);
110
+ return line;
111
+ }
@@ -13,6 +13,7 @@ const STAGES = new Set([
13
13
  'runtime.prepare', 'activation', 'harness.check', 'connection.start', 'connection.poll', 'connection.stop', 'status.read', 'rollback', 'management.request',
14
14
  ]);
15
15
  const REASONS = new Set([
16
+ 'session-log-corrupt',
16
17
  'stream-closed-before-open', 'stream-failed-before-open', 'stream-failed',
17
18
  'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT', 'EPIPE',
18
19
  'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET',
@@ -25,7 +25,7 @@ import { t } from './i18n.mjs';
25
25
  import { watchHarnessMux } from './harness-mux.mjs';
26
26
  import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
27
27
  import { PromptFailureTracker } from './prompt-failure-tracker.mjs';
28
- import { isSessionNotFound } from './session-error.mjs';
28
+ import { isSessionLogCorrupt, isSessionNotFound } from './session-error.mjs';
29
29
 
30
30
  // Every channel plugin runs in the same Host process. Sharing ownership by
31
31
  // Host identity (or an explicitly configured HTTP origin) prevents clients
@@ -1406,9 +1406,15 @@ export class HarnessClient {
1406
1406
  }
1407
1407
 
1408
1408
  // A diagnostic recheck must not hide the original failure or cancellation.
1409
- async #confirmedArchiveError(sessionId, options, cause) {
1409
+ async #confirmedSessionError(sessionId, options, cause) {
1410
1410
  try {
1411
1411
  if (await this.#isSessionArchived(sessionId, options)) return sessionArchivedError(sessionId, cause);
1412
+ if (isSessionLogCorrupt(cause)) {
1413
+ return Object.assign(new Error('Stored Session log is unreadable', { cause }), {
1414
+ code: 'session-unreadable', method: cause.method,
1415
+ details: { reason: 'session-log-corrupt' },
1416
+ });
1417
+ }
1412
1418
  } catch (error) {
1413
1419
  if (options?.signal?.aborted) throw options.signal.reason ?? error;
1414
1420
  }
@@ -1422,7 +1428,7 @@ export class HarnessClient {
1422
1428
  if (options?.signal?.aborted) throw options.signal.reason ?? error;
1423
1429
  if (error instanceof HarnessRpcError
1424
1430
  && (['internal', 'gateway/internal'].includes(error.code) || isSessionNotFound(error.code))) {
1425
- throw await this.#confirmedArchiveError(payload.sessionId, { signal: options?.signal }, error) ?? error;
1431
+ throw await this.#confirmedSessionError(payload.sessionId, { signal: options?.signal }, error) ?? error;
1426
1432
  }
1427
1433
  throw error;
1428
1434
  }
@@ -2098,7 +2104,7 @@ export class HarnessClient {
2098
2104
  if (!ownership?.stopRequested && !harnessTurnSucceeded(tracker.reason)) {
2099
2105
  const failure = harnessTurnError(tracker.reason);
2100
2106
  if (failure.code === 'turn-blocked') {
2101
- throw await this.#confirmedArchiveError(sessionId, { signal }, failure) ?? failure;
2107
+ throw await this.#confirmedSessionError(sessionId, { signal }, failure) ?? failure;
2102
2108
  }
2103
2109
  throw failure;
2104
2110
  }
@@ -2132,7 +2138,7 @@ export class HarnessClient {
2132
2138
  .map((event) => event.seq));
2133
2139
  if (blockedSeq > checkedBlockedSeq) {
2134
2140
  checkedBlockedSeq = blockedSeq;
2135
- const archived = await this.#confirmedArchiveError(sessionId, { signal });
2141
+ const archived = await this.#confirmedSessionError(sessionId, { signal });
2136
2142
  if (archived) throw archived;
2137
2143
  }
2138
2144
  }
@@ -2140,7 +2146,7 @@ export class HarnessClient {
2140
2146
  if (Date.now() - lastProgressAt < timeoutMs) continue;
2141
2147
 
2142
2148
  if (!ownership?.stopRequested) {
2143
- const archived = await this.#confirmedArchiveError(sessionId, { signal });
2149
+ const archived = await this.#confirmedSessionError(sessionId, { signal });
2144
2150
  if (archived) throw archived;
2145
2151
  }
2146
2152
 
@@ -83,6 +83,11 @@ export default {
83
83
  '否': 'No',
84
84
  '用法:/workspace 工作区序号或绝对路径':
85
85
  'Usage: /workspace Workspace index or absolute path',
86
+ '查看或切换工作区': 'View or switch Workspace',
87
+ '/workspace 或 /ws 查看可切换的工作区(点按钮切换)':
88
+ '/workspace or /ws View switchable Workspaces (tap a button to switch)',
89
+ '/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)':
90
+ '/workspacelist, /wsl, /workspaces Workspace-list aliases (same as /ws)',
86
91
  '当前机器人暂不支持切换工作区。': 'This bot does not support switching Workspaces yet.',
87
92
  '工作区已切换为:{workspace}': 'Workspace switched to: {workspace}',
88
93
  '{message}\n用法:/workspace 工作区序号或绝对路径':
@@ -1,5 +1,8 @@
1
1
  // English translations (shared-c area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请先在“绑定 DS Bot”中解除绑定,再切换会话或工作目录。': 'Unbind in “Bind DS Bot” before switching the Session or working directory.',
4
+ '当前会话日志已损坏,无法继续读取。请先到 DSH 查看任务状态,再发送 /new 创建新会话;原会话记录会保留。': 'The current Session log is corrupt and cannot be read. Check the task status in DSH before sending /new to create a new Session; the original records will be preserved.',
5
+ '绑定会话的日志已损坏,已切换到新会话并继续处理本条消息。原会话记录已保留,历史上下文不会自动带入。': 'The bound Session log is corrupt. Switched to a new Session to continue processing this message. The original records are preserved; previous context is not carried over automatically.',
3
6
  '微信': 'Weixin',
4
7
  '飞书': 'Feishu',
5
8
  '钉钉': 'DingTalk',
@@ -8,6 +8,12 @@ export default {
8
8
  '开启一个全新会话': 'Start a brand-new Session',
9
9
  '压缩当前会话的较早上下文': 'Compact the earlier context of the current Session',
10
10
  '切换工作区': 'Switch Workspace',
11
+ // /ws workspace picker card: one tap switches, the pressed card is re-marked in place.
12
+ '选择要切换的工作区(共 {count} 个):': 'Choose a Workspace to switch to ({count} total):',
13
+ '这个列表已过期,请重新发送 /ws。': 'This list has expired. Send /ws again.',
14
+ '正在切换工作区,请稍候。': 'Switching Workspaces, one moment.',
15
+ '已经在工作区:{workspace}': 'Already in this Workspace: {workspace}',
16
+ '暂时无法切换工作区,请稍后重试。': 'Could not switch Workspaces right now. Try again later.',
11
17
  '列出工作区绝对路径': 'List Workspace absolute paths',
12
18
  '列出会话 ID 和标题': 'List Session IDs and titles',
13
19
  '将当前聊天绑定到指定会话': 'Bind the current chat to a specific Session',
@@ -75,6 +75,11 @@ export default {
75
75
  '否': 'Нет',
76
76
  '用法:/workspace 工作区序号或绝对路径':
77
77
  'Использование: /workspace <номер или абсолютный путь рабочей области>',
78
+ '查看或切换工作区': 'Просмотреть или переключить рабочую область',
79
+ '/workspace 或 /ws 查看可切换的工作区(点按钮切换)':
80
+ '/workspace или /ws Показать доступные рабочие области (нажмите кнопку для переключения)',
81
+ '/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)':
82
+ '/workspacelist, /wsl, /workspaces Псевдонимы списка рабочих областей (как /ws)',
78
83
  '当前机器人暂不支持切换工作区。': 'Этот бот пока не поддерживает переключение рабочей области.',
79
84
  '工作区已切换为:{workspace}': 'Рабочая область переключена на: {workspace}',
80
85
  '{message}\n用法:/workspace 工作区序号或绝对路径':
@@ -1,5 +1,8 @@
1
1
  // Russian translations (shared-c area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请先在“绑定 DS Bot”中解除绑定,再切换会话或工作目录。': 'Сначала снимите привязку в разделе «Привязать DS Bot», затем смените сессию или рабочий каталог.',
4
+ '当前会话日志已损坏,无法继续读取。请先到 DSH 查看任务状态,再发送 /new 创建新会话;原会话记录会保留。': 'Журнал текущей сессии повреждён и не может быть прочитан. Проверьте состояние задачи в DSH, прежде чем отправлять /new для создания новой сессии; исходные записи будут сохранены.',
5
+ '绑定会话的日志已损坏,已切换到新会话并继续处理本条消息。原会话记录已保留,历史上下文不会自动带入。': 'Журнал привязанной сессии повреждён. Выполнено переключение на новую сессию для обработки этого сообщения. Исходные записи сохранены; предыдущий контекст автоматически не переносится.',
3
6
  '微信': 'Weixin',
4
7
  '飞书': 'Feishu',
5
8
  '钉钉': 'DingTalk',
@@ -6,6 +6,11 @@ export default {
6
6
  '开启一个全新会话': 'Начать новую сессию',
7
7
  '压缩当前会话的较早上下文': 'Сжать ранний контекст текущей сессии',
8
8
  '切换工作区': 'Переключить рабочую область',
9
+ '选择要切换的工作区(共 {count} 个):': 'Выберите рабочую область (всего: {count}):',
10
+ '这个列表已过期,请重新发送 /ws。': 'Этот список устарел. Отправьте /ws ещё раз.',
11
+ '正在切换工作区,请稍候。': 'Рабочая область переключается. Подождите.',
12
+ '已经在工作区:{workspace}': 'Уже в рабочей области: {workspace}',
13
+ '暂时无法切换工作区,请稍后重试。': 'Не удалось переключить рабочую область. Повторите попытку позже.',
9
14
  '列出工作区绝对路径': 'Показать абсолютные пути рабочих областей',
10
15
  '列出会话 ID 和标题': 'Показать ID и заголовки сессий',
11
16
  '将当前聊天绑定到指定会话': 'Привязать текущий чат к указанной сессии',
@@ -1,7 +1,7 @@
1
1
  import { isSessionNotFound } from './session-error.mjs';
2
2
  import { connectionHint, extractConnectionEvidence, messageDiagnosticError, runtimeDiagnosticDetails } from './connection-error.mjs';
3
+ import { createFailureReferenceId } from './delivery-failure-log.mjs';
3
4
  import { diagnosticFields } from './diagnostic-details.mjs';
4
- import { randomUUID } from 'node:crypto';
5
5
 
6
6
  import { t } from './i18n.mjs';
7
7
 
@@ -75,6 +75,8 @@ const FAILURE_MESSAGES = Object.freeze({
75
75
  '任务被意外中断,本次未完成。请重试。',
76
76
  SESSION_NOT_FOUND:
77
77
  '当前会话已不存在。请发送 /new 创建新会话后重试。',
78
+ SESSION_UNREADABLE:
79
+ '当前会话日志已损坏,无法继续读取。请先到 DSH 查看任务状态,再发送 /new 创建新会话;原会话记录会保留。',
78
80
  SESSION_ARCHIVED:
79
81
  '当前会话已归档,无法继续处理。有命令权限时可发送 /new 创建新会话;否则请联系管理员在 DSH 中取消归档,或为你开启命令权限。',
80
82
  SESSION_BUSY:
@@ -147,6 +149,7 @@ function failureCode(error, details) {
147
149
  if (code === 'turn-blocked') return 'TURN_BLOCKED';
148
150
  if (['turn-interrupted', 'turn-aborted'].includes(code)) return 'TURN_INTERRUPTED';
149
151
  if (isSessionNotFound(code)) return 'SESSION_NOT_FOUND';
152
+ if (code === 'session-unreadable') return 'SESSION_UNREADABLE';
150
153
  if (code === 'session-archived') return 'SESSION_ARCHIVED';
151
154
  if (code === 'agent-busy') return 'SESSION_BUSY';
152
155
  if (code === 'workspace-session-stale') return 'SESSION_STALE';
@@ -198,7 +201,7 @@ function transportFailureCode(error, details) {
198
201
  function safeReferenceId(value) {
199
202
  return typeof value === 'string' && /^[A-Z0-9-]{6,40}$/u.test(value)
200
203
  ? value
201
- : `MF-${randomUUID().slice(0, 8).toUpperCase()}`;
204
+ : createFailureReferenceId();
202
205
  }
203
206
 
204
207
  function safeFailureReason(value) {
@@ -1,3 +1,11 @@
1
1
  export function isSessionNotFound(code) {
2
2
  return code === 'session-not-found' || code === 'session/not-found';
3
3
  }
4
+
5
+ // Older Hosts report corrupt logs as generic internal errors. Only recognize
6
+ // storage/format signatures on Session RPCs, never arbitrary internal failures.
7
+ export function isSessionLogCorrupt(error) {
8
+ return ['internal', 'gateway/internal'].includes(error?.code)
9
+ && ['session.history', 'session.prompt'].includes(error?.method)
10
+ && /stored log is corrupt|stored session "[^"\n]+" is corrupt|SessionFormatError:/u.test(error?.message ?? '');
11
+ }