@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
@@ -46,14 +46,29 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
46
46
  '/conv 或 /conversation 查看当前对话工作区',
47
47
  '/conv 工作区绝对路径或序号 设置当前对话专属工作区',
48
48
  '/conv clear 清除专属工作区,回到 bot 默认工作区',
49
- ], { aliases: ['conversation', 'thread'] }),
49
+ ], {
50
+ // Aliases stay typeable and stay in /help, but the native Telegram menu
51
+ // lists each command once; B16 in the command UX audit.
52
+ aliases: [
53
+ { name: 'conversation', menuVisible: false },
54
+ { name: 'thread', menuVisible: false },
55
+ ],
56
+ }),
50
57
  defineCatalogCommand('workspacelist', '列出工作区绝对路径', [
51
58
  '/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)',
52
- ], { aliases: ['workspaces', 'wsl'], menuVisible: false }),
59
+ ], {
60
+ // Aliases stay typeable and stay in /help, but the native Telegram menu
61
+ // lists each command once; B16 in the command UX audit.
62
+ aliases: [
63
+ { name: 'workspaces', menuVisible: false },
64
+ { name: 'wsl', menuVisible: false },
65
+ ],
66
+ menuVisible: false,
67
+ }),
53
68
  defineCatalogCommand('sessionlist', '列出会话 ID 和标题', [
54
69
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
55
70
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
56
- ], { aliases: ['sessions'] }),
71
+ ], { aliases: [{ name: 'sessions', menuVisible: false }] }),
57
72
  defineCatalogCommand('session', '将当前聊天绑定到指定会话', [
58
73
  '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
59
74
  ]),
@@ -62,7 +77,7 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
62
77
  ]),
63
78
  defineCatalogCommand('reasoninglist', '按序号列出当前模型可用推理等级', [
64
79
  '/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级',
65
- ], { aliases: ['reasonings'] }),
80
+ ], { aliases: [{ name: 'reasonings', menuVisible: false }] }),
66
81
  defineCatalogCommand('reasoning', '查看或切换当前推理等级', [
67
82
  '/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级',
68
83
  ]),
@@ -72,7 +87,7 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
72
87
  ]),
73
88
  defineCatalogCommand('presetlist', '列出可用 Agent Preset', [
74
89
  '/presetlist 或 /presets 按序号列出可用 Agent Preset',
75
- ], { aliases: ['presets'] }),
90
+ ], { aliases: [{ name: 'presets', menuVisible: false }] }),
76
91
  defineCatalogCommand('preset', '查看或设置新会话 Agent Preset', [
77
92
  '/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset',
78
93
  '纯数字 ID:/preset id:<ID>',
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Decode a stored conversation key back into the parts a caller can reason
3
+ * about: whether it is a direct chat, a group, or a thread, plus the ids
4
+ * inside it.
5
+ *
6
+ * The keys are written by the channel codecs in `./route.mjs` (and by the
7
+ * channels that still own their own key shape), so this reader accepts every
8
+ * shape we know about. It never invents a key: an unknown or malformed string
9
+ * yields `null` and the caller treats the conversation as unidentified.
10
+ *
11
+ * Known shapes:
12
+ * direct:dm:<userId> Matrix direct chat (user ids contain `:`)
13
+ * direct:<id> generic direct chat; whether <id> names
14
+ * the peer user or the DM channel depends
15
+ * on the channel (see SENDER_DIRECT_CHANNELS)
16
+ * p2p:<userId> Feishu / Weixin / WeCom app / DingTalk
17
+ * c2c:<openid> QQ private chat
18
+ * group:<chatId> group without a thread
19
+ * group:<chatId>:thread:<threadId> Feishu thread (older shape)
20
+ * group:<chatId>:<threadId> Telegram forum topic, Slack thread
21
+ * group:room:<roomId>[$<root>] Matrix room, `$` separates a thread root
22
+ */
23
+
24
+ /**
25
+ * @typedef {Object} ParsedConversationKey
26
+ * @property {'dm'|'group'|'thread'} chatType
27
+ * @property {?string} chatId
28
+ * @property {?string} threadId
29
+ * @property {?string} senderId
30
+ */
31
+
32
+ const SEP = ':';
33
+
34
+ /** Everything before the first separator is the scope. */
35
+ function scopeOf(key) {
36
+ const index = key.indexOf(SEP);
37
+ return index === -1 ? key : key.slice(0, index);
38
+ }
39
+
40
+ function restOf(key) {
41
+ const index = key.indexOf(SEP);
42
+ return index === -1 ? '' : key.slice(index + 1);
43
+ }
44
+
45
+ /**
46
+ * Channels whose `direct:<id>` suffix is the peer user id. Elsewhere (Slack,
47
+ * Discord, WhatsApp, iMessage, email, ...) it names the DM channel or chat,
48
+ * so reporting it as a sender would point a consumer at the wrong user.
49
+ */
50
+ const SENDER_DIRECT_CHANNELS = new Set(['telegram', 'wecom']);
51
+
52
+ function dm(chatId, senderId) {
53
+ return { chatType: 'dm', chatId: chatId || null, threadId: null, senderId: senderId || null };
54
+ }
55
+
56
+ function parseDirect(rest, channel) {
57
+ // `direct:dm:<id>` — Matrix keeps an explicit `dm` marker; the user id
58
+ // itself (`@alice:example.org`) contains the separator, so take it whole.
59
+ if (rest.startsWith('dm' + SEP)) {
60
+ const id = rest.slice(3);
61
+ return id ? dm(null, id) : null;
62
+ }
63
+ return dm(rest, SENDER_DIRECT_CHANNELS.has(channel) ? rest : null);
64
+ }
65
+
66
+ /** `p2p:` and `c2c:` keys are written per sender by every channel that uses them. */
67
+ function parsePeer(rest) {
68
+ return dm(null, rest);
69
+ }
70
+
71
+ function parseMatrixRoom(rest) {
72
+ const body = rest.slice('room:'.length);
73
+ const mark = body.indexOf('$');
74
+ if (mark === -1) {
75
+ return body ? { chatType: 'group', chatId: body, threadId: null, senderId: null } : null;
76
+ }
77
+ const chatId = body.slice(0, mark);
78
+ const threadId = body.slice(mark + 1);
79
+ if (!chatId || !threadId) return null;
80
+ return { chatType: 'thread', chatId, threadId, senderId: null };
81
+ }
82
+
83
+ function parseGroup(rest) {
84
+ // Matrix rooms keep their own prefix; everything else is `<chatId>[:<thread>]`
85
+ // or the explicit `<chatId>:thread:<threadId>` form.
86
+ if (rest.startsWith('room:')) return parseMatrixRoom(rest);
87
+ const parts = rest.split(SEP);
88
+ const chatId = parts[0];
89
+ if (!chatId) return null;
90
+ if (parts.length === 1) return { chatType: 'group', chatId, threadId: null, senderId: null };
91
+ if (parts.length === 3 && parts[1] === 'thread' && parts[2]) {
92
+ return { chatType: 'thread', chatId, threadId: parts[2], senderId: null };
93
+ }
94
+ if (parts.length === 2 && parts[1]) {
95
+ return { chatType: 'thread', chatId, threadId: parts[1], senderId: null };
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * Decode one conversation key.
102
+ * @param {unknown} key stored conversation key
103
+ * @param {{channel?: string}} [options] channel that stored the key; decides
104
+ * whether a `direct:<id>` suffix is a user id or a chat id
105
+ * @returns {?ParsedConversationKey} parts, or null when the key is not ours
106
+ */
107
+ export function parseConversationKey(key, { channel } = {}) {
108
+ if (typeof key !== 'string' || key === '' || key.length > 1_024) return null;
109
+ const scope = scopeOf(key);
110
+ const rest = restOf(key);
111
+ if (rest === '') return null;
112
+ if (scope === 'direct') return parseDirect(rest, channel);
113
+ if (scope === 'p2p' || scope === 'c2c') return parsePeer(rest);
114
+ if (scope === 'group') return parseGroup(rest);
115
+ return null;
116
+ }
@@ -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
+ }
@@ -13,6 +13,40 @@ const EXTENSION_KEYS = Object.freeze([
13
13
 
14
14
  const PENDING_MESSAGE_LIMIT = 200;
15
15
 
16
+ /**
17
+ * How many conversations remember their last author. One entry per
18
+ * conversation, overwritten on every inbound message, so this is a bounded
19
+ * map of "who spoke here last" -- never a transcript.
20
+ */
21
+ const AUTHOR_LIMIT = 500;
22
+
23
+ /**
24
+ * Keep only what identifies the speaker: no message text, no display extras.
25
+ * A missing or malformed id drops the entry instead of storing a half record.
26
+ */
27
+ function normalizeAuthor(value) {
28
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
29
+ const senderId = typeof value.senderId === 'string' ? value.senderId : '';
30
+ if (!senderId) return null;
31
+ const author = { senderId, isBot: value.isBot === true };
32
+ if (typeof value.senderName === 'string' && value.senderName) author.senderName = value.senderName;
33
+ if (typeof value.senderUsername === 'string' && value.senderUsername) author.senderUsername = value.senderUsername;
34
+ if (typeof value.at === 'string' && value.at) author.at = value.at;
35
+ return author;
36
+ }
37
+
38
+ function normalizeAuthors(value) {
39
+ const authors = {};
40
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return authors;
41
+ const keys = Object.keys(value);
42
+ for (const key of keys.slice(Math.max(0, keys.length - AUTHOR_LIMIT))) {
43
+ if (typeof key !== 'string' || !key) continue;
44
+ const author = normalizeAuthor(value[key]);
45
+ if (author) authors[key] = author;
46
+ }
47
+ return authors;
48
+ }
49
+
16
50
  const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
17
51
 
18
52
  /**
@@ -71,9 +105,13 @@ function normalizeState(value) {
71
105
  // An empty queue leaves no key behind, so an untouched state file keeps the
72
106
  // shape earlier versions wrote.
73
107
  const pendingMessages = normalizePendingMessages(value.pendingMessages);
108
+ // Authors are optional: a state file written before this field existed loads
109
+ // unchanged and simply reports no author.
110
+ const authors = normalizeAuthors(value.authors);
74
111
  const normalized = {
75
112
  version: 1,
76
113
  sessions,
114
+ ...(Object.keys(authors).length ? { authors } : {}),
77
115
  ...(pendingMessages.length ? { pendingMessages } : {}),
78
116
  ...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
79
117
  seenMessageIds: Array.isArray(value.seenMessageIds)
@@ -164,6 +202,30 @@ export class ConversationStateStore {
164
202
  return this.#state.sessions[key] ?? null;
165
203
  }
166
204
 
205
+ /** The last speaker of a conversation, or null when none was recorded. */
206
+ authorFor(key) {
207
+ const author = this.#state.authors?.[key];
208
+ return author ? structuredClone(author) : null;
209
+ }
210
+
211
+ /**
212
+ * Remember who last spoke in a conversation. Persisted so the answer survives
213
+ * a restart; overwritten on every inbound message and bounded by AUTHOR_LIMIT.
214
+ */
215
+ async rememberAuthor(key, value) {
216
+ const author = normalizeAuthor({ at: new Date().toISOString(), ...value });
217
+ if (typeof key !== 'string' || !key || !author) return null;
218
+ const authors = this.#state.authors ??= {};
219
+ delete authors[key];
220
+ authors[key] = author;
221
+ const keys = Object.keys(authors);
222
+ if (keys.length > AUTHOR_LIMIT) {
223
+ for (const stale of keys.slice(0, keys.length - AUTHOR_LIMIT)) delete authors[stale];
224
+ }
225
+ await this.#persist();
226
+ return structuredClone(author);
227
+ }
228
+
167
229
  async setSession(key, sessionId) {
168
230
  this.#state.sessions[key] = sessionId;
169
231
  await this.#persist();
@@ -59,6 +59,40 @@ export const CONFIG_ISSUE_LABELS = Object.freeze({
59
59
  // Map keys are replaced with zero-based positions to avoid exposing identities.
60
60
  const CONFIG_FIELD = /^(?:\$|version|accounts(?:\[\d{1,10}\](?:\.(?:accountId|ownerUserId|botId|tokenRef|baseUrl))?)?|(?:workspaces|agentPresets|models)(?:\[\d{1,10}\]\.(?:key|value))?|deliveryTargets(?:\[\d{1,10}\]\.(?:key|targets(?:\[\d{1,10}\])?))?)$/;
61
61
 
62
+ // A local-library failure is often only distinguishable by its message:
63
+ // `QRCode.toDataURL is not a function` and `String required as first argument`
64
+ // are different bugs with identical error types and reasons. Free-form text is
65
+ // never forwarded; only messages that already look like a known local-library
66
+ // diagnostic are admitted, so a service error carrying a URL, a credential or a
67
+ // piece of user content stays out of the report entirely.
68
+ const DIAGNOSTIC_MESSAGE_SHAPES = [
69
+ // `QRCode.toDataURL is not a function`, `PNG.sync.write is not a constructor`
70
+ /^(?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]* is not a (?:function|constructor)$/u,
71
+ // node-qrcode validating its argument
72
+ /^String required as first argument$/u,
73
+ // property access on undefined inside the encoder
74
+ /^Cannot read propert(?:y|ies) .{1,100}$/u,
75
+ // zlib: `invalid stored block lengths`, `incorrect header check`, `Invalid data`
76
+ /^(?:invalid|incorrect|unexpected|unknown|bad)\s+[A-Za-z][A-Za-z0-9 _-]{2,80}$/iu,
77
+ // pngjs / buffer: `padding not multiple of block size`, `buffer write failed`
78
+ /^[A-Za-z][A-Za-z0-9 _-]{2,60}(?: not multiple of block size| failed)$/u,
79
+ ];
80
+ const DIAGNOSTIC_MESSAGE_DENY = /(?:token|secret|password|passwd|authorization|bearer|cookie)/iu;
81
+ const DIAGNOSTIC_MESSAGE_URL = /\b(?:[a-z][a-z0-9+.-]*:\/\/)\S*/iu;
82
+ const DIAGNOSTIC_MESSAGE_EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+/u;
83
+ const DIAGNOSTIC_MESSAGE_OPAQUE = /\b[A-Za-z0-9_\-+/=]{32,}\b/u;
84
+
85
+ export function safeDiagnosticMessage(value) {
86
+ if (typeof value !== 'string') return undefined;
87
+ const text = value.replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();
88
+ if (!/^[\x20-\x7e]+$/u.test(text)) return undefined;
89
+ if (!DIAGNOSTIC_MESSAGE_SHAPES.some(shape => shape.test(text))) return undefined;
90
+ if (DIAGNOSTIC_MESSAGE_DENY.test(text)) return undefined;
91
+ if (DIAGNOSTIC_MESSAGE_URL.test(text) || DIAGNOSTIC_MESSAGE_EMAIL.test(text)) return undefined;
92
+ if (DIAGNOSTIC_MESSAGE_OPAQUE.test(text)) return undefined;
93
+ return text;
94
+ }
95
+
62
96
  export function normalizeDiagnosticDetails(value) {
63
97
  if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
64
98
  const result = {};
@@ -104,6 +138,10 @@ export function normalizeDiagnosticDetails(value) {
104
138
  if (typeof value.pluginVersion === 'string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.pluginVersion)
105
139
  && value.pluginVersion.length <= 64) result.pluginVersion = value.pluginVersion;
106
140
  if (['succeeded', 'failed', 'not-attempted', 'unknown'].includes(value.rollback)) result.rollback = value.rollback;
141
+ if (typeof value.causeMessage === 'string') {
142
+ const message = safeDiagnosticMessage(value.causeMessage);
143
+ if (message) result.causeMessage = message;
144
+ }
107
145
  if (typeof value.hint === 'string' && value.hint.trim()) result.hint = value.hint.trim().slice(0, 500);
108
146
  return result;
109
147
  }
@@ -27,6 +27,25 @@ const EXPIRY_RETRY_MAX_MS = 5 * 60_000;
27
27
  const RESOLVED_ROUTE_TTL_MS = 5 * 60_000;
28
28
  const MAX_RESOLVED_ROUTES = 2_048;
29
29
 
30
+ /**
31
+ * How a card-driven decision ended, so a channel card can tell "the decision is
32
+ * in" from "still submitting", "try again" and "this card can never work again".
33
+ *
34
+ * A transient Host/RPC failure keeps the approval pending, which makes the
35
+ * press retryable: the card must hand its keyboard back instead of staying
36
+ * `claimed` forever behind a "still submitting" toast.
37
+ */
38
+ export const APPROVAL_SUBMIT_RESULT = Object.freeze({
39
+ /** The Host accepted the decision; the approval is gone from the queue. */
40
+ SUBMITTED: 'submitted',
41
+ /** Another decision is in flight; keep the card until its outcome is known. */
42
+ BUSY: 'busy',
43
+ /** Nothing was decided and the approval is still pending: press again. */
44
+ RETRYABLE: 'retryable',
45
+ /** The approval is no longer decidable here (resolved, expired, closed). */
46
+ GONE: 'gone',
47
+ });
48
+
30
49
  function cleanText(value) {
31
50
  return typeof value === 'string' ? value.trim() : '';
32
51
  }
@@ -72,6 +91,7 @@ export function harnessApprovalText(payload, {
72
91
  toolCall,
73
92
  requiresMention = false,
74
93
  maxArgumentsLength = 6_000,
94
+ hasButtons = false,
75
95
  } = {}) {
76
96
  if (!validHarnessApproval(payload)) return null;
77
97
  const callId = cleanText(payload.callId);
@@ -90,8 +110,13 @@ export function harnessApprovalText(payload, {
90
110
  ];
91
111
  const reason = printableText(payload.reason);
92
112
  if (reason) lines.push(t('原因:{reason}', { reason }));
93
- lines.push('', t(APPROVAL_PROMPT));
94
- if (requiresMention) lines.push('', t('群聊中请 @机器人 后发送审批决定。'));
113
+ // A button card carries the intent itself: asking the user to type a decision
114
+ // (or to @ the bot in a group) would be misleading next to the buttons. The
115
+ // plain-text path below stays byte-identical to what it has always sent.
116
+ if (!hasButtons) {
117
+ lines.push('', t(APPROVAL_PROMPT));
118
+ if (requiresMention) lines.push('', t('群聊中请 @机器人 后发送审批决定。'));
119
+ }
95
120
  return lines.join('\n');
96
121
  }
97
122
 
@@ -236,7 +261,9 @@ export class HarnessApprovalQueue {
236
261
  return;
237
262
  }
238
263
  if (!decision) {
239
- await send(t(APPROVAL_PROMPT));
264
+ // A button card already tells the user how to decide; repeating
265
+ // the type-the-decision prompt would contradict its buttons.
266
+ if (!pending.interactiveCard) await send(t(APPROVAL_PROMPT));
240
267
  return;
241
268
  }
242
269
  await this.#submit(pending, decision);
@@ -366,6 +393,10 @@ export class HarnessApprovalQueue {
366
393
  deliveryCompleted: false,
367
394
  replyTail: null,
368
395
  submitting: false,
396
+ // Set by a channel renderer once an interactive card really reached the
397
+ // user. It means the card owns the decision guidance and the receipt, so
398
+ // the plain-text prompts/receipts below must stay quiet.
399
+ interactiveCard: false,
369
400
  inactive: false,
370
401
  resolving: false,
371
402
  closedOutcome: null,
@@ -396,13 +427,20 @@ export class HarnessApprovalQueue {
396
427
  * (e.g. Feishu approve/reject). Returns false when no matching pending
397
428
  * approval is found. Callers may pass the acting user to enforce that only
398
429
  * the originating actor can decide.
430
+ *
431
+ * Pass `{ detailed: true }` to get an {@link APPROVAL_SUBMIT_RESULT} instead of
432
+ * a boolean: an interactive card has to tell a retryable submission failure
433
+ * apart from an in-flight decision, one that landed, or an invalid card.
399
434
  */
400
- async submitByApprovalId(approvalId, outcome, { actor } = {}) {
435
+ async submitByApprovalId(approvalId, outcome, { actor, detailed = false } = {}) {
401
436
  const pending = this.#byId.get(cleanText(approvalId));
402
- if (!pending || pending.inactive || pending.resolving || pending.submitting) return false;
403
- if (actor !== undefined && pending.actor !== actor) return false;
404
- await this.#submit(pending, outcome);
405
- return true;
437
+ const gone = detailed ? APPROVAL_SUBMIT_RESULT.GONE : false;
438
+ if (!pending || pending.inactive || pending.resolving) return gone;
439
+ if (actor !== undefined && pending.actor !== actor) return gone;
440
+ if (pending.submitting) return detailed ? APPROVAL_SUBMIT_RESULT.BUSY : false;
441
+ const result = await this.#submit(pending, outcome);
442
+ if (!detailed) return true;
443
+ return result ?? APPROVAL_SUBMIT_RESULT.RETRYABLE;
406
444
  }
407
445
 
408
446
  async handleResolved(resolution) {
@@ -583,18 +621,19 @@ export class HarnessApprovalQueue {
583
621
  await this.#transition(next, async () => {
584
622
  await this.#notifyResolved(pending, 'resolved', send);
585
623
  });
586
- return;
624
+ return APPROVAL_SUBMIT_RESULT.GONE;
587
625
  }
588
- if (pending.inactive) return;
626
+ if (pending.inactive) return APPROVAL_SUBMIT_RESULT.GONE;
589
627
  pending.submitting = false;
590
628
  this.#logger.error?.(`[dsh-im:${this.#label}] failed to submit an approval:`, error);
591
629
  // The deadline passed while this decision was in flight.
592
630
  if (pending.expired) {
593
631
  await this.#expire(pending);
594
- return;
632
+ return APPROVAL_SUBMIT_RESULT.GONE;
595
633
  }
596
634
  await pending.send(t('审批提交失败,请重新回复「批准」或「拒绝」。')).catch(() => undefined);
597
- return;
635
+ // The approval is still pending: the caller may offer the press again.
636
+ return APPROVAL_SUBMIT_RESULT.RETRYABLE;
598
637
  }
599
638
 
600
639
  const send = pending.send;
@@ -602,6 +641,7 @@ export class HarnessApprovalQueue {
602
641
  await this.#transition(next, async () => {
603
642
  await this.#notifyResolved(pending, outcome, send);
604
643
  });
644
+ return APPROVAL_SUBMIT_RESULT.SUBMITTED;
605
645
  }
606
646
 
607
647
  async #notifyResolved(pending, outcome, send = pending.send) {
@@ -610,11 +650,16 @@ export class HarnessApprovalQueue {
610
650
  // resolved event cannot replace the confirmed result or notify twice.
611
651
  pending.resolutionNotified = true;
612
652
  const text = approvalOutcomeText(outcome);
653
+ let deliveredByPresentation = false;
613
654
  try {
614
- await pending.onResolved?.(text);
655
+ // A card renderer returns true when it already edited the original message
656
+ // into the receipt; the separate terminal text would then be a duplicate
657
+ // (and the pending.send may have been swapped by an interim text reply).
658
+ deliveredByPresentation = (await pending.onResolved?.(text, outcome)) === true;
615
659
  } catch (error) {
616
660
  this.#logger.warn?.(`[dsh-im:${this.#label}] failed to update a resolved approval:`, error);
617
661
  }
662
+ if (deliveredByPresentation) return;
618
663
  await send(text).catch(() => undefined);
619
664
  }
620
665
 
@@ -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 });
@@ -1341,6 +1351,14 @@ export class HarnessClient {
1341
1351
  return created.workspace.workspaceId;
1342
1352
  }
1343
1353
 
1354
+ /**
1355
+ * This client can name a Session up front (`session.create` accepts `sessionId`),
1356
+ * which lets a caller bind a conversation before prompt assembly runs.
1357
+ */
1358
+ get canChooseSessionId() {
1359
+ return true;
1360
+ }
1361
+
1344
1362
  async createSession(options = {}) {
1345
1363
  const { agentPreset: requestedPreset, ...rpcOptions } = options;
1346
1364
  const workspace = rpcOptions.workspace ?? this.#workspace;
@@ -1352,6 +1370,11 @@ export class HarnessClient {
1352
1370
  : { workspaceId: await this.workspaceId(rpcOptions) };
1353
1371
  const agentPreset = requestedPreset !== undefined ? requestedPreset : this.#agentPreset;
1354
1372
  if (agentPreset != null) payload.agentPreset = agentPreset;
1373
+ // The caller may name the Session: it then knows the identity before the
1374
+ // Session exists, which is the only way prompt assembly can see it.
1375
+ if (typeof options.sessionId === 'string' && options.sessionId !== '') {
1376
+ payload.sessionId = options.sessionId;
1377
+ }
1355
1378
  const created = await this.rpc('session.create', payload, 30_000, rpcOptions);
1356
1379
  if (typeof created?.sessionId !== 'string' || !created.sessionId) {
1357
1380
  throw new HarnessTransportError('harness-response-invalid', 'session.create');
@@ -1434,6 +1457,46 @@ export class HarnessClient {
1434
1457
  }
1435
1458
  }
1436
1459
 
1460
+ /**
1461
+ * 提交超时后的入库确认:session.history 是持久账本,按 promptRpcId 找回我们的
1462
+ * 持久化痕迹(已执行的 user/message,或已入队待执行的 agent/inbox/spliced
1463
+ * 回执)即视为提交已成功,让 ask() 继续等回复而不是误报失败。
1464
+ * 确认探测自身的失败一律吞掉——它们不能掩盖或改变原始提交超时的定性;
1465
+ * 唯独取消例外:取消原因必须优先于超时透出。
1466
+ */
1467
+ async #confirmPromptSubmit(sessionId, promptRpcId, { signal } = {}) {
1468
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1469
+ if (signal?.aborted) return false;
1470
+ try {
1471
+ const history = await this.#sessionRpc('session.history', {
1472
+ sessionId,
1473
+ maxMessages: 50,
1474
+ }, 30_000, { signal });
1475
+ const confirmed = (history?.events ?? []).some((entry) => {
1476
+ const event = entry?.event ?? entry;
1477
+ if (event?.type === 'user/message') {
1478
+ return event?.data?.source?.rpcId === promptRpcId;
1479
+ }
1480
+ // queue 模式下消息可能已持久入队但尚未产生 user/message:
1481
+ // agent/inbox/spliced 的 inserted[].source.rpcId 就是入队回执。
1482
+ if (event?.type === 'agent/inbox/spliced') {
1483
+ return (event?.data?.inserted ?? [])
1484
+ .some((message) => message?.source?.rpcId === promptRpcId);
1485
+ }
1486
+ return false;
1487
+ });
1488
+ if (confirmed) return true;
1489
+ } catch (probeError) {
1490
+ // 取消优先于超时定性:最后一次探测期间被取消时,循环后面没有
1491
+ // sleep 再检查 abort,必须在这里把取消原因抛出,不能被超时覆盖。
1492
+ if (signal?.aborted) throw signal.reason ?? probeError;
1493
+ // 其余账本探测失败不改变定性:本轮未确认,继续轮询或最终按原超时上报。
1494
+ }
1495
+ if (attempt < 4) await sleep(2_000, signal);
1496
+ }
1497
+ return false;
1498
+ }
1499
+
1437
1500
  async sessionExists(sessionId, options = {}) {
1438
1501
  // Archived Sessions still exist. Returning false here would silently bind
1439
1502
  // the conversation to a new Session; reading their active log can also fail.
@@ -2037,8 +2100,28 @@ export class HarnessClient {
2037
2100
  ...timeZoneFields,
2038
2101
  }, 30_000, { rpcId: promptRpcId, signal });
2039
2102
  };
2103
+ // 30 秒提交窗口到期只说明 Host 忙到没来得及应答,prompt 可能早已入队。
2104
+ // 先按 promptRpcId 回查持久账本,确认入库就继续等回复;确认不到才把
2105
+ // 原始超时错误向上抛,由文案层标注「提交请求超时、是否送达未知」。
2106
+ const submitPrompt = async (promptContent) => {
2107
+ try {
2108
+ await sendPrompt(promptContent);
2109
+ } catch (error) {
2110
+ if (!isPromptSubmitTimeout(error) || signal?.aborted) throw error;
2111
+ let confirmed = false;
2112
+ try {
2113
+ confirmed = await this.#confirmPromptSubmit(sessionId, promptRpcId, { signal });
2114
+ } catch (confirmError) {
2115
+ // 确认途中被取消时恢复调用方的取消语义(与图片暂存路径一致)。
2116
+ if (signal?.aborted) throw signal.reason ?? confirmError;
2117
+ throw error;
2118
+ }
2119
+ if (!confirmed) throw error;
2120
+ diagnostic.submissionState = 'accepted';
2121
+ }
2122
+ };
2040
2123
  try {
2041
- await sendPrompt(content);
2124
+ await submitPrompt(content);
2042
2125
  } catch (error) {
2043
2126
  // The Host refuses image blocks for a non-vision model before any
2044
2127
  // durable user message exists. Re-deliver the same bytes the way
@@ -2073,7 +2156,7 @@ export class HarnessClient {
2073
2156
  ...contentWithoutImages(baseContent),
2074
2157
  { type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
2075
2158
  ], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
2076
- await sendPrompt(fallbackPrompt);
2159
+ await submitPrompt(fallbackPrompt);
2077
2160
  }
2078
2161
  promptAccepted = true;
2079
2162
  diagnostic.submissionState = 'accepted';