@xmanrui/dsh-im 5.10.0 → 5.11.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 (114) hide show
  1. package/README.en.md +39 -5
  2. package/README.md +42 -5
  3. package/bin/dsh-im.mjs +65 -0
  4. package/docs/client-integration.md +4 -0
  5. package/lib/client.js +1202 -95
  6. package/lib/index.js +365 -339
  7. package/package.json +7 -6
  8. package/plugin-src/client/access-policy-settings.js +210 -12
  9. package/plugin-src/client/bot-general-settings.js +44 -3
  10. package/plugin-src/client/i18n-ru.js +85 -0
  11. package/plugin-src/client/i18n.js +83 -0
  12. package/plugin-src/client/im-channels.js +419 -0
  13. package/plugin-src/client/index.js +33 -1
  14. package/plugin-src/client/styles.js +7 -7
  15. package/plugin-src/client/update-panel.js +2 -1
  16. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  17. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  18. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  19. package/plugin-src/host/channels/feishu/production.mjs +39 -10
  20. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  21. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  22. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  23. package/plugin-src/host/channels/qq/production.mjs +30 -11
  24. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  26. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  27. package/plugin-src/host/channels/shared/production.mjs +14 -1
  28. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  30. package/plugin-src/host/channels/slack/production.mjs +28 -10
  31. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  33. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  34. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  35. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  36. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  37. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  38. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  39. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  40. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  41. package/plugin-src/host/delivery-service.mjs +3 -4
  42. package/plugin-src/host/delivery-suggestions.mjs +3 -1
  43. package/plugin-src/host/harness-connection.mjs +2 -1
  44. package/plugin-src/host/harness-peer.mjs +3 -1
  45. package/plugin-src/host/index.mjs +8 -1
  46. package/plugin-src/host/modern-harness-api.mjs +5 -1
  47. package/plugin-src/host/root-scope.mjs +32 -0
  48. package/plugin-src/host/session-sync-coordinator.mjs +2 -1
  49. package/plugin-src/management-rpc.mjs +18 -2
  50. package/scripts/verify-package.mjs +36 -7
  51. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  52. package/src/channels/dingtalk/state-store.mjs +56 -0
  53. package/src/channels/discord/discord-api.mjs +2 -1
  54. package/src/channels/feishu/bridge.mjs +154 -58
  55. package/src/channels/feishu/feishu-cards.mjs +10 -4
  56. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  57. package/src/channels/feishu/message-utils.mjs +106 -30
  58. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  59. package/src/channels/feishu/state-store.mjs +14 -0
  60. package/src/channels/matrix/matrix-api.mjs +2 -1
  61. package/src/channels/qq/qq-bridge.mjs +105 -14
  62. package/src/channels/qq/state-store.mjs +13 -1
  63. package/src/channels/shared/access-policy.mjs +60 -7
  64. package/src/channels/shared/bot-workspace-store.mjs +155 -3
  65. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  66. package/src/channels/shared/channel-capabilities.mjs +44 -0
  67. package/src/channels/shared/command-catalog.mjs +68 -3
  68. package/src/channels/shared/command-permission.mjs +6 -2
  69. package/src/channels/shared/conversation-state-store.mjs +16 -0
  70. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  71. package/src/channels/shared/deferred-delivery.mjs +4 -0
  72. package/src/channels/shared/diagnostic-details.mjs +6 -1
  73. package/src/channels/shared/failure-log-file.mjs +79 -0
  74. package/src/channels/shared/harness-client.mjs +111 -6
  75. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  76. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  77. package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
  78. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  79. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  80. package/src/channels/shared/i18n-en.mjs +2 -0
  81. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  82. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  83. package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
  84. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  85. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  86. package/src/channels/shared/i18n-ru.mjs +2 -0
  87. package/src/channels/shared/inbound-access.mjs +10 -0
  88. package/src/channels/shared/markdown-chunks.mjs +5 -0
  89. package/src/channels/shared/message-failure.mjs +22 -1
  90. package/src/channels/shared/new-command.mjs +158 -4
  91. package/src/channels/shared/plan-goal-command.mjs +132 -0
  92. package/src/channels/shared/qrcode.mjs +5 -0
  93. package/src/channels/shared/reply-content.mjs +102 -0
  94. package/src/channels/shared/reset-command.mjs +46 -0
  95. package/src/channels/shared/semantic/artifact.mjs +133 -29
  96. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  97. package/src/channels/shared/session-nav-command.mjs +999 -0
  98. package/src/channels/shared/session-ring-support.mjs +184 -0
  99. package/src/channels/shared/session-ring.mjs +202 -0
  100. package/src/channels/shared/session-title.mjs +11 -0
  101. package/src/channels/shared/status-command.mjs +2 -1
  102. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  103. package/src/channels/shared/workspace-command.mjs +567 -31
  104. package/src/channels/shared/workspace-session.mjs +39 -3
  105. package/src/channels/slack/slack-api.mjs +2 -1
  106. package/src/channels/telegram/config-store.mjs +10 -2
  107. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  108. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  109. package/src/channels/wecom/state-store.mjs +13 -1
  110. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  111. package/src/channels/wecom-app/state-store.mjs +13 -1
  112. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  113. package/src/channels/weixin/state-store.mjs +13 -1
  114. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -9,22 +9,62 @@ const WORKSPACE_COMMAND = /^\/(?:workspace|ws)(?:\s+([\s\S]+))?$/i;
9
9
  const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)(?:\s+([\s\S]+))?$/i;
10
10
  const THREAD_WORKSPACE_COMMAND = /^\/(?:conv|conversation|thread)(?:\s+([\s\S]+))?$/i;
11
11
  const SESSION_LIST_COMMAND = /^\/(?:sessionlist|sessions)(?:\s+([\s\S]+))?$/i;
12
- const SESSION_BIND_PREFIX = /^\/session(?=$|\s)/i;
13
- const SESSION_BIND_COMMAND = /^\/session[ \t]+([^\s]+)$/i;
12
+ // `/session` stays the advertised name. Some clients own a slash command of the
13
+ // same name and grab the input box before the bot sees it, so `/sess` is
14
+ // accepted as a short alias that survives those clients.
15
+ const SESSION_BIND_PREFIX = /^\/(?:session|sess)(?=$|\s)/i;
16
+ const SESSION_BIND_COMMAND = /^\/(?:session|sess)[ \t]+([^\s]+)$/i;
14
17
  const MAX_WORKSPACE_PATH_LENGTH = 4_096;
15
18
  const MAX_COMMAND_MESSAGE_LENGTH = 1_800;
16
19
  const MAX_SESSION_ID_LENGTH = 256;
17
20
  const UNSAFE_DISPLAY_TEXT = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
18
21
  const UNSAFE_DISPLAY_TEXT_GLOBAL = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;
19
- const SESSION_BIND_USAGE = '用法:/session Session ID 或当前工作区序号(/session N)';
22
+ const SESSION_BIND_USAGE = '用法:/session Session ID、当前工作区序号(/session N)或会话标题关键词';
20
23
  const SESSION_LIST_USAGE = [
21
24
  '用法:',
22
25
  '/sessionlist 列出当前工作区会话',
26
+ '/sessionlist --all 跨工作区汇总列出会话(每个工作区默认显示 10 个)',
27
+ '/sessionlist --all --limit N 跨工作区汇总列出会话,每个工作区显示前 N 个',
23
28
  '/sessionlist --limit N 列出当前工作区前 N 个会话(N 为正整数)',
29
+ '/sessionlist --archived 一并列出已归档会话(序号仍只对应未归档会话)',
24
30
  '/sessionlist 工作区序号 按 /workspacelist 序号列出会话',
25
31
  '/sessionlist 工作区绝对路径 列出指定工作区会话',
26
32
  '不带工作区参数时,默认列出当前对话的有效工作区(未设置对话专属工作区时即 bot 默认工作区)。',
27
33
  ].join('\n');
34
+ // Archiving is a Harness capability (workspace.archiveSession); the command only
35
+ // carries the request, so an older Host answers with a clear "not supported".
36
+ const SESSION_ARCHIVE_PREFIX = /^\/(?:sessionarchive|sessarchive)(?=$|\s)/i;
37
+ const SESSION_ARCHIVE_COMMAND = /^\/(?:sessionarchive|sessarchive)(?:[ \t]+([^\s]+))?(?:[ \t]+(--?stop))?$/i;
38
+ const SESSION_ARCHIVE_USAGE = '用法:/sessionarchive Session ID 归档一个会话;/sessionarchive 序号 只预览该序号对应的会话(编号会随列表变化,归档请用完整 ID)。加 --stop 可让 DSH 先停止该会话正在运行的任务';
39
+ // An index is resolved against a list that shifts as soon as a new Session
40
+ // appears (the command's own turn can add one), so an index only previews the
41
+ // target: archiving is destructive and has to name the Session explicitly.
42
+ const SESSION_ARCHIVE_PREVIEW = '按序号归档只做预览:/sessionarchive {index} 现在对应这条会话。';
43
+ const SESSION_ARCHIVE_PREVIEW_HINT = '(编号会随会话列表变化,所以不按序号直接归档;确认归档请发送:/sessionarchive {sessionId})';
44
+ const SESSION_LIST_ALL_FLAG = '--all';
45
+ const SESSION_LIST_LIMIT_FLAG = '--limit';
46
+ const SESSION_LIST_ARCHIVED_FLAG = '--archived';
47
+ const ALL_WORKSPACES_DEFAULT_LIMIT = 10;
48
+ const MAX_SESSION_TITLE_QUERY_LENGTH = 120;
49
+ const MAX_SESSION_TITLE_MATCHES = 10;
50
+ const SESSION_ID_PREFIX = /^session-/iu;
51
+ const SESSION_LIST_ALL_HEADER = '跨工作区会话({workspaces} 个工作区,共 {sessions} 个会话):';
52
+ const SESSION_LIST_ALL_CURRENT = '当前工作区:{workspace}';
53
+ const SESSION_LIST_ALL_SKIPPED = '另有 {count} 个工作区暂时无法读取,未包含在汇总中。';
54
+ const SESSION_LIST_GROUP_HEADER = '{workspace}({count} 个会话)';
55
+ const SESSION_LIST_GROUP_TRUNCATED = '(共 {total} 个,显示前 {shown} 个;用 --limit N 调整)';
56
+ const SESSION_LIST_GROUP_EMPTY = '该工作区暂无会话。';
57
+ const SESSION_LIST_GROUP_INVALID = '({count} 条会话记录无效,已跳过)';
58
+ const SESSION_LIST_ARCHIVED_HIDDEN = '(已隐藏 {count} 条归档会话,用 --archived 查看)';
59
+ const SESSION_LIST_ARCHIVED_HEADER = '归档会话(只能用完整 Session ID 绑定):';
60
+ const SESSION_TITLE_AMBIGUOUS = '标题包含「{keyword}」的会话有多个,请改用完整 Session ID 绑定:';
61
+ const SESSION_TITLE_REMOTE = '标题包含「{keyword}」的会话位于其他工作区,请使用完整 Session ID 绑定:';
62
+ const SESSION_TITLE_SEARCH_INCOMPLETE = '部分工作区暂时无法读取,搜索结果可能不完整;请使用完整 Session ID 绑定:';
63
+ const SESSION_TITLE_SEARCH_INCOMPLETE_MISS = '部分工作区暂时无法读取,未能确认标题包含「{keyword}」的会话。请稍后重试或使用完整 Session ID。';
64
+ const SESSION_TITLE_AMBIGUOUS_TRUNCATED = '匹配较多,只显示前 {count} 个,请使用更精确的关键词。';
65
+ const SESSION_TITLE_MISS = '没有标题包含「{keyword}」的会话,请先执行 /sessionlist --all 查看完整 Session ID。';
66
+ const SESSION_TITLE_BIND_FAILED = '按标题匹配到「{title}」(ID: {sessionId},工作区: {workspace}),但 Harness 当前无法接管这个会话,请稍后重试或用完整 Session ID 绑定。';
67
+ const SESSION_TITLE_ARCHIVED = '标题包含「{keyword}」的会话已归档,按标题绑定不会接管归档会话,请用完整 Session ID 绑定:';
28
68
 
29
69
  function commandResult(message, messages = [message], extra = {}) {
30
70
  return { handled: true, message, messages, ...extra };
@@ -52,15 +92,47 @@ function validSessionId(value) {
52
92
  export function parseSessionListArgument(value) {
53
93
  const argument = typeof value === 'string' ? value.trim() : '';
54
94
  if (!argument) return { selector: '', limit: null };
55
- if (!argument.toLowerCase().startsWith('--limit')) {
56
- return { selector: argument, limit: null };
95
+ const tokens = argument.split(/[ \t]+/u);
96
+ const head = tokens[0].toLowerCase();
97
+ // Anything that does not start with a flag stays a workspace selector; only
98
+ // the flags below are parsed, so a path can never be mistaken for one. An
99
+ // unknown flag is a usage error instead of being echoed as a bad path.
100
+ const flags = new Set([SESSION_LIST_ALL_FLAG, SESSION_LIST_LIMIT_FLAG, SESSION_LIST_ARCHIVED_FLAG]);
101
+ if (!flags.has(head)) {
102
+ return head.startsWith('--')
103
+ ? { error: t(SESSION_LIST_USAGE) }
104
+ : { selector: argument, limit: null };
57
105
  }
58
- const match = /^--limit[ \t]+(\d+)$/iu.exec(argument);
59
- const limit = match ? Number(match[1]) : null;
60
- if (!Number.isSafeInteger(limit) || limit < 1) {
61
- return { error: t(SESSION_LIST_USAGE) };
106
+ let all = false;
107
+ let archived = false;
108
+ let limit = null;
109
+ for (let index = 0; index < tokens.length;) {
110
+ const token = tokens[index].toLowerCase();
111
+ if (token === SESSION_LIST_ALL_FLAG && !all) {
112
+ all = true;
113
+ index += 1;
114
+ continue;
115
+ }
116
+ if (token === SESSION_LIST_ARCHIVED_FLAG && !archived) {
117
+ archived = true;
118
+ index += 1;
119
+ continue;
120
+ }
121
+ const raw = token === SESSION_LIST_LIMIT_FLAG ? tokens[index + 1] : undefined;
122
+ const parsed = typeof raw === 'string' && /^\d+$/u.test(raw) ? Number(raw) : null;
123
+ if (limit !== null || parsed === null
124
+ || !Number.isSafeInteger(parsed) || parsed < 1) {
125
+ return { error: t(SESSION_LIST_USAGE) };
126
+ }
127
+ limit = parsed;
128
+ index += 2;
62
129
  }
63
- return { selector: '', limit };
130
+ // Optional flags are only present when they were asked for, so the shape of a
131
+ // plain `--limit N` (or bare) result stays what earlier callers compare to.
132
+ const result = { selector: '', limit };
133
+ if (all) result.all = true;
134
+ if (archived) result.archived = true;
135
+ return result;
64
136
  }
65
137
 
66
138
  async function existingWorkspacePath(value) {
@@ -116,7 +188,13 @@ export async function workspacePathSnapshot(harness, { includeTitles = false, in
116
188
  const withEntries = includeTitles && typeof harness.listWorkspaceEntries === 'function';
117
189
  const listed = await (withEntries ? harness.listWorkspaceEntries(options) : harness.listWorkspaces(options));
118
190
  const currentValue = await conversationSessionWorkspace(harness, conversationKey, options);
119
- const current = await existingWorkspacePath(currentValue);
191
+ let current = await existingWorkspacePath(currentValue);
192
+ if (!current && typeof conversationKey === 'string' && conversationKey
193
+ && typeof harness?.currentWorkspace === 'function') {
194
+ // A conversation override can outlive its directory. /sessionlist falls
195
+ // back to the bot workspace in that case; keep this snapshot consistent.
196
+ current = await existingWorkspacePath(harness.currentWorkspace());
197
+ }
120
198
  const entries = await Promise.all((Array.isArray(listed) ? listed : []).map(async (item) => ({
121
199
  path: await existingWorkspacePath(withEntries ? item?.path : item),
122
200
  title: withEntries ? safeDisplayText(item?.title) : '',
@@ -275,24 +353,92 @@ function formatSessionRelativeTime(value) {
275
353
  return t('{year}年{month}月{day}日', { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() });
276
354
  }
277
355
 
278
- function sessionListMessage(workspace, sessions, { currentWorkspace = false } = {}) {
279
- const rows = sessions.map((session) => {
280
- const sessionId = safeDisplayText(session?.sessionId);
281
- if (!sessionId) throw new TypeError('Harness returned an invalid session id');
282
- const title = session?.summaryAvailable === false
283
- ? t('标题暂不可用')
284
- : safeDisplayText(session?.title) || t('暂无标题');
285
- const timeText = formatSessionRelativeTime(session?.time);
286
- const annotation = `${timeText ? ` · ${timeText}` : ''}${session?.archived === true ? t('(已归档)') : ''}`;
287
- return `${title}${annotation}\n ID: ${sessionId}`;
288
- });
289
- if (rows.length === 0) return t(`工作区:{workspace}
356
+ /**
357
+ * One numbered row. `boundSessionId` marks the Session this conversation is
358
+ * already bound to, so a reader can tell where they are instead of looking up
359
+ * the ID by hand.
360
+ */
361
+ // Archived Sessions are listed only on request: the default answer should be
362
+ // the set a user can bind by index, not the whole history of the Workspace.
363
+ function splitArchived(sessions) {
364
+ const live = [];
365
+ const archived = [];
366
+ for (const session of sessions) {
367
+ (session?.archived === true ? archived : live).push(session);
368
+ }
369
+ return { live, archived };
370
+ }
371
+
372
+ function sessionRowText(session, boundSessionId) {
373
+ const sessionId = safeDisplayText(session?.sessionId);
374
+ if (!sessionId) throw new TypeError('Harness returned an invalid session id');
375
+ const title = session?.summaryAvailable === false
376
+ ? t('标题暂不可用')
377
+ : safeDisplayText(session?.title) || t('暂无标题');
378
+ const timeText = formatSessionRelativeTime(session?.time);
379
+ const annotation = `${timeText ? ` · ${timeText}` : ''}`
380
+ + `${session?.archived === true ? t('(已归档)') : ''}`
381
+ + `${boundSessionId && sessionId === boundSessionId ? t('(当前绑定)') : ''}`;
382
+ return `${title}${annotation}\n ID: ${sessionId}`;
383
+ }
384
+
385
+ function sessionListRow(session, index, boundSessionId) {
386
+ return `${index}. ${sessionRowText(session, boundSessionId)}`;
387
+ }
388
+
389
+ /**
390
+ * Rows for one Workspace. Only the live (non-archived) Sessions get numbers,
391
+ * and those numbers are the same order `/session N` resolves against, so the
392
+ * list and the index always agree. Archived rows are unnumbered extras.
393
+ */
394
+ function sessionRows(sessions, boundSessionId, { includeArchived = false } = {}) {
395
+ const { live, archived } = splitArchived(sessions);
396
+ const rows = [];
397
+ let invalid = 0;
398
+ for (const [index, session] of live.entries()) {
399
+ try {
400
+ rows.push(sessionListRow(session, index + 1, boundSessionId));
401
+ } catch {
402
+ invalid += 1;
403
+ }
404
+ }
405
+ const extra = [];
406
+ if (includeArchived) {
407
+ for (const session of archived) {
408
+ try {
409
+ extra.push(`• ${sessionRowText(session, boundSessionId)}`);
410
+ } catch {
411
+ invalid += 1;
412
+ }
413
+ }
414
+ }
415
+ return { rows, extra, archivedCount: archived.length, invalid };
416
+ }
417
+
418
+ function sessionListMessage(
419
+ workspace,
420
+ { rows, extra, archivedCount, invalid },
421
+ { currentWorkspace = false, includeArchived = false } = {},
422
+ ) {
423
+ const notes = [];
424
+ if (invalid > 0) notes.push(t(SESSION_LIST_GROUP_INVALID, { count: invalid }));
425
+ if (!includeArchived && archivedCount > 0) {
426
+ notes.push(t(SESSION_LIST_ARCHIVED_HIDDEN, { count: archivedCount }));
427
+ }
428
+ if (rows.length === 0 && extra.length === 0) {
429
+ const head = t('工作区:{workspace}', { workspace });
430
+ return notes.length
431
+ ? [head, ...notes].join('\n')
432
+ : t(`工作区:{workspace}
290
433
  该工作区暂无会话。`, { workspace });
434
+ }
291
435
  return [
292
436
  t('工作区:{workspace}', { workspace }),
293
437
  t('会话({count}):', { count: rows.length }),
294
438
  '',
295
- ...rows.map((row, index) => `${index + 1}. ${row}`),
439
+ ...rows,
440
+ ...(extra.length > 0 ? ['', t(SESSION_LIST_ARCHIVED_HEADER), ...extra] : []),
441
+ ...(notes.length > 0 ? ['', ...notes] : []),
296
442
  '',
297
443
  currentWorkspace
298
444
  ? t('绑定用法:/session Session ID 或当前工作区序号(/session N)')
@@ -310,6 +456,112 @@ async function currentSessionListWorkspace(harness, conversationKey) {
310
456
  return current ?? null;
311
457
  }
312
458
 
459
+ // Read-only decoration: a stale bot scope must degrade to "no marker" instead of
460
+ // failing a listing that is otherwise complete.
461
+ export function boundSessionIdFor(source, conversationKey) {
462
+ if (typeof source?.sessionFor !== 'function') return '';
463
+ if (typeof conversationKey !== 'string' || !conversationKey) return '';
464
+ try {
465
+ const sessionId = safeDisplayText(source.sessionFor(conversationKey));
466
+ return validSessionId(sessionId) ? sessionId : '';
467
+ } catch {
468
+ return '';
469
+ }
470
+ }
471
+
472
+ function workspaceGroupLabel(path, titles) {
473
+ const title = safeDisplayText(titles?.[path]);
474
+ return title ? `${title} — ${path}` : path;
475
+ }
476
+
477
+ async function listWorkspaceSessionsOrNull(harness, workspace) {
478
+ try {
479
+ const listed = await harness.listWorkspaceSessions(workspace);
480
+ if (!listed || !Array.isArray(listed.sessions)) {
481
+ throw new TypeError('Harness returned an invalid workspace session list');
482
+ }
483
+ return listed.sessions;
484
+ } catch (error) {
485
+ if (error?.code === 'workspace-bot-not-found') throw error;
486
+ return null;
487
+ }
488
+ }
489
+
490
+ /**
491
+ * `/sessionlist --all`: every registered Workspace in one answer. A Workspace
492
+ * whose session list cannot be read is left out rather than failing the whole
493
+ * command, so one broken Workspace never hides the others.
494
+ */
495
+ async function allWorkspacesSessionListing(harness, limit, conversationKey, { includeArchived = false } = {}) {
496
+ if (typeof harness?.listWorkspaces !== 'function'
497
+ && typeof harness?.listWorkspaceEntries !== 'function') {
498
+ return commandResult(t('当前机器人暂不支持跨工作区列出会话。'));
499
+ }
500
+ const { current, paths, titles } = await workspacePathSnapshot(harness, {
501
+ includeTitles: true,
502
+ conversationKey,
503
+ });
504
+ if (paths.length === 0) {
505
+ return commandResult(t('当前 Harness Host 上没有仍然存在的已登记工作区。'));
506
+ }
507
+ const boundSessionId = boundSessionIdFor(harness, conversationKey);
508
+ const shownLimit = Number.isSafeInteger(limit) && limit > 0 ? limit : ALL_WORKSPACES_DEFAULT_LIMIT;
509
+ const groups = [];
510
+ let failed = 0;
511
+ for (const workspace of paths) {
512
+ const sessions = await listWorkspaceSessionsOrNull(harness, workspace);
513
+ if (sessions === null) {
514
+ failed += 1;
515
+ continue;
516
+ }
517
+ groups.push({ workspace, sessions });
518
+ }
519
+ harness.assertWorkspaceScope?.();
520
+ if (groups.length === 0) {
521
+ return commandResult(t('暂时无法获取工作区会话列表,请稍后重试。'));
522
+ }
523
+ // Rows are built once per group and every count below derives from them, so a
524
+ // group's total, its truncation note and its invalid-record note always agree.
525
+ const prepared = groups.map((group) => ({
526
+ ...group,
527
+ ...sessionRows(group.sessions, boundSessionId, { includeArchived }),
528
+ }));
529
+ const total = prepared.reduce((sum, group) => sum + group.rows.length, 0);
530
+ const lines = [t(SESSION_LIST_ALL_HEADER, { workspaces: prepared.length, sessions: total })];
531
+ if (current) lines.push(t(SESSION_LIST_ALL_CURRENT, { workspace: current }));
532
+ if (failed > 0) lines.push(t(SESSION_LIST_ALL_SKIPPED, { count: failed }));
533
+ lines.push(t(`绑定用法:/session Session ID
534
+ 提示:/session N 只按机器人当前工作区的序号绑定。`));
535
+ for (const group of prepared) {
536
+ const label = workspaceGroupLabel(group.workspace, titles);
537
+ lines.push('', t(SESSION_LIST_GROUP_HEADER, {
538
+ workspace: `${label}${group.workspace === current ? t('(当前)') : ''}`,
539
+ count: group.rows.length,
540
+ }));
541
+ const shown = group.rows.slice(0, shownLimit);
542
+ lines.push(...shown);
543
+ if (group.extra.length > 0) {
544
+ lines.push('', t(SESSION_LIST_ARCHIVED_HEADER), ...group.extra);
545
+ }
546
+ if (group.invalid > 0) {
547
+ lines.push(t(SESSION_LIST_GROUP_INVALID, { count: group.invalid }));
548
+ } else if (group.rows.length === 0 && group.extra.length === 0) {
549
+ lines.push(t(SESSION_LIST_GROUP_EMPTY));
550
+ }
551
+ if (!includeArchived && group.archivedCount > 0) {
552
+ lines.push(t(SESSION_LIST_ARCHIVED_HIDDEN, { count: group.archivedCount }));
553
+ }
554
+ if (shown.length < group.rows.length) {
555
+ lines.push(t(SESSION_LIST_GROUP_TRUNCATED, {
556
+ total: group.rows.length,
557
+ shown: shown.length,
558
+ }));
559
+ }
560
+ }
561
+ const message = lines.join('\n');
562
+ return commandResult(message, splitWorkspaceCommandMessage(message));
563
+ }
564
+
313
565
  async function runSessionListCommand(match, harness, conversationKey) {
314
566
  const request = parseSessionListArgument(match[1]);
315
567
  if (request.error) return commandResult(request.error);
@@ -317,6 +569,11 @@ async function runSessionListCommand(match, harness, conversationKey) {
317
569
  return commandResult(t('当前机器人暂不支持列出工作区会话。'));
318
570
  }
319
571
  try {
572
+ if (request.all) {
573
+ return await allWorkspacesSessionListing(harness, request.limit, conversationKey, {
574
+ includeArchived: request.archived === true,
575
+ });
576
+ }
320
577
  const resolved = await resolveSessionListWorkspace(request.selector, harness, { conversationKey });
321
578
  if (resolved.error) return commandResult(resolved.error);
322
579
  const listed = await harness.listWorkspaceSessions(resolved.workspace);
@@ -326,11 +583,17 @@ async function runSessionListCommand(match, harness, conversationKey) {
326
583
  harness.assertWorkspaceScope?.();
327
584
  const workspace = normalizedWorkspacePath(listed.workspace) ?? resolved.workspace;
328
585
  const currentWorkspace = await currentSessionListWorkspace(harness, conversationKey);
329
- const sessions = request.limit === null
330
- ? listed.sessions
331
- : listed.sessions.slice(0, request.limit);
332
- const message = sessionListMessage(workspace, sessions, {
586
+ // Rows are numbered over the live Sessions (the order `/session N` binds
587
+ // against); --limit only truncates what is shown, so a displayed number is
588
+ // always the number that binding uses.
589
+ const includeArchived = request.archived === true;
590
+ const listing = sessionRows(listed.sessions, boundSessionIdFor(harness, conversationKey), {
591
+ includeArchived,
592
+ });
593
+ const rows = request.limit === null ? listing.rows : listing.rows.slice(0, request.limit);
594
+ const message = sessionListMessage(workspace, { ...listing, rows }, {
333
595
  currentWorkspace: workspace === currentWorkspace,
596
+ includeArchived,
334
597
  });
335
598
  return commandResult(message, splitWorkspaceCommandMessage(message));
336
599
  } catch (error) {
@@ -368,9 +631,104 @@ function sessionBindErrorMessage(error) {
368
631
  return t('暂时无法绑定会话,请稍后重试。');
369
632
  }
370
633
 
634
+ // A single token that is neither an index nor an explicit Session ID is a
635
+ // title keyword. Anything with control characters or an absurd length is not a
636
+ // query at all, so it keeps failing as a malformed /session argument.
637
+ function sessionTitleQuery(value) {
638
+ return typeof value === 'string'
639
+ && value.length > 0
640
+ && value.length <= MAX_SESSION_TITLE_QUERY_LENGTH
641
+ && validSessionId(value)
642
+ && !SESSION_ID_PREFIX.test(value);
643
+ }
644
+
645
+ /**
646
+ * Title search across Workspaces. `workspacePathSnapshot` puts the
647
+ * conversation's effective Workspace first, so a local hit is visited before a
648
+ * same-named Session elsewhere and can be preferred by the caller. One
649
+ * unreadable Workspace is counted and skipped; a stale bot scope aborts.
650
+ *
651
+ * Archived Sessions are never bound by a keyword: a keyword is a guess, and
652
+ * moving an archived Session into this chat's Workspace is exactly the kind of
653
+ * side effect a guess must not have. They are collected separately so the
654
+ * answer can name them instead of pretending nothing matched.
655
+ */
656
+ async function sessionTitleMatches(harness, conversationKey, keyword) {
657
+ const { current, paths, titles } = await workspacePathSnapshot(harness, {
658
+ includeTitles: true,
659
+ conversationKey,
660
+ });
661
+ const needle = keyword.toLowerCase();
662
+ const matches = [];
663
+ const archivedMatches = [];
664
+ let archivedExactSessionId = null;
665
+ let exactSessionId = null;
666
+ let failed = 0;
667
+ for (const workspace of paths) {
668
+ const sessions = await listWorkspaceSessionsOrNull(harness, workspace);
669
+ if (sessions === null) {
670
+ failed += 1;
671
+ continue;
672
+ }
673
+ for (const session of sessions) {
674
+ const sessionId = session?.sessionId;
675
+ if (!validSessionId(sessionId)) continue;
676
+ const archived = session?.archived === true;
677
+ // An ID remains an exact match even when its title is empty or does not
678
+ // contain the ID. Keep looking after the title candidate cap as well.
679
+ if (sessionId === keyword) {
680
+ if (archived) archivedExactSessionId = sessionId;
681
+ else exactSessionId = sessionId;
682
+ }
683
+ const title = safeDisplayText(session?.title);
684
+ if (!title) continue;
685
+ if (!title.toLowerCase().includes(needle)) continue;
686
+ const candidate = {
687
+ sessionId,
688
+ title,
689
+ workspace,
690
+ workspaceLabel: workspaceGroupLabel(workspace, titles),
691
+ };
692
+ if (archived) {
693
+ if (archivedMatches.length <= MAX_SESSION_TITLE_MATCHES) archivedMatches.push(candidate);
694
+ } else if (matches.length <= MAX_SESSION_TITLE_MATCHES) {
695
+ matches.push(candidate);
696
+ }
697
+ }
698
+ }
699
+ harness.assertWorkspaceScope?.();
700
+ return { current, matches, archivedMatches, archivedExactSessionId, failed, exactSessionId };
701
+ }
702
+
703
+ function sessionTitleCandidatesMessage(keyword, matches, header = SESSION_TITLE_AMBIGUOUS) {
704
+ const shown = matches.slice(0, MAX_SESSION_TITLE_MATCHES);
705
+ const lines = [t(header, { keyword }), ''];
706
+ for (const [index, match] of shown.entries()) {
707
+ lines.push(
708
+ `${index + 1}. ${match.title}`,
709
+ t('工作区:{workspace}', { workspace: match.workspaceLabel }),
710
+ ` ID: ${match.sessionId}`,
711
+ );
712
+ }
713
+ lines.push('');
714
+ if (matches.length > shown.length) {
715
+ lines.push(t(SESSION_TITLE_AMBIGUOUS_TRUNCATED, { count: shown.length }));
716
+ }
717
+ lines.push(t(SESSION_BIND_USAGE));
718
+ return lines.join('\n');
719
+ }
720
+
371
721
  async function runSessionBindCommand(command, harness, conversationKey) {
372
722
  const match = SESSION_BIND_COMMAND.exec(command);
373
723
  let sessionId = match?.[1];
724
+ if (typeof sessionId === 'string'
725
+ && (sessionId.length > MAX_SESSION_ID_LENGTH || UNSAFE_DISPLAY_TEXT.test(sessionId))) {
726
+ return commandResult(t(SESSION_BIND_USAGE));
727
+ }
728
+ let titleQuery = false;
729
+ let titleSearchIncomplete = false;
730
+ let titleBindingWorkspace = null;
731
+ let titleBinding = null;
374
732
  if (typeof sessionId === 'string' && /^\d+$/u.test(sessionId)) {
375
733
  // Use the same effective-workspace resolver as /sessionlist, so its indexes
376
734
  // cannot select a session from the bot default after /conv sets an override.
@@ -387,12 +745,15 @@ async function runSessionBindCommand(command, harness, conversationKey) {
387
745
  throw new TypeError('Harness returned an invalid workspace session list');
388
746
  }
389
747
  harness.assertWorkspaceScope?.();
748
+ // Same rule as the listing: an index addresses the live (non-archived)
749
+ // Sessions it numbers, so an archived Session is only reachable by ID.
750
+ const { live } = splitArchived(listed.sessions);
390
751
  const position = Number(sessionId);
391
752
  if (!Number.isSafeInteger(position) || position < 1
392
- || position > listed.sessions.length) {
753
+ || position > live.length) {
393
754
  return commandResult(t('会话序号不存在,请先执行 /sessionlist 查看序号。'));
394
755
  }
395
- const selectedSessionId = listed.sessions[position - 1]?.sessionId;
756
+ const selectedSessionId = live[position - 1]?.sessionId;
396
757
  if (!validSessionId(selectedSessionId)) {
397
758
  throw new TypeError('Harness returned an invalid session id');
398
759
  }
@@ -403,6 +764,63 @@ async function runSessionBindCommand(command, harness, conversationKey) {
403
764
  }
404
765
  return commandResult(t('暂时无法获取会话列表,请稍后重试。'));
405
766
  }
767
+ } else if (sessionTitleQuery(sessionId)
768
+ && typeof harness?.listWorkspaceSessions === 'function'
769
+ && (typeof harness?.listWorkspaces === 'function'
770
+ || typeof harness?.listWorkspaceEntries === 'function')) {
771
+ titleQuery = true;
772
+ try {
773
+ const {
774
+ current, matches, archivedMatches, archivedExactSessionId, failed, exactSessionId,
775
+ } = await sessionTitleMatches(harness, conversationKey, sessionId);
776
+ titleSearchIncomplete = failed > 0;
777
+ const [unique] = matches;
778
+ if (exactSessionId) {
779
+ sessionId = exactSessionId;
780
+ titleQuery = false;
781
+ } else if (matches.length === 0 && archivedMatches.length > 0 && !archivedExactSessionId) {
782
+ // Only archived Sessions matched: name them instead of binding, and let
783
+ // the reader decide whether to bind one by its full ID.
784
+ const message = sessionTitleCandidatesMessage(
785
+ sessionId,
786
+ archivedMatches,
787
+ SESSION_TITLE_ARCHIVED,
788
+ );
789
+ return commandResult(message, splitWorkspaceCommandMessage(message));
790
+ } else if (matches.length > 1) {
791
+ const message = sessionTitleCandidatesMessage(
792
+ sessionId,
793
+ matches,
794
+ failed > 0 ? SESSION_TITLE_SEARCH_INCOMPLETE : SESSION_TITLE_AMBIGUOUS,
795
+ );
796
+ return commandResult(message, splitWorkspaceCommandMessage(message));
797
+ } else if (matches.length === 1) {
798
+ // Only the current conversation's Workspace may be adopted by title.
799
+ // Pass that constraint to the binding transaction so it preserves the
800
+ // bot default and rejects a Workspace change during the search.
801
+ if (failed === 0 && current && unique.workspace === current) {
802
+ sessionId = unique.sessionId;
803
+ titleQuery = false;
804
+ titleBindingWorkspace = current;
805
+ titleBinding = unique;
806
+ } else {
807
+ const message = sessionTitleCandidatesMessage(
808
+ sessionId,
809
+ matches,
810
+ failed > 0 ? SESSION_TITLE_SEARCH_INCOMPLETE : SESSION_TITLE_REMOTE,
811
+ );
812
+ return commandResult(message, splitWorkspaceCommandMessage(message));
813
+ }
814
+ }
815
+ // Zero matches: fall through to the legacy "treat the token as a Session
816
+ // ID" path, so an ID that simply has no title match still binds.
817
+ } catch (error) {
818
+ if (error?.code === 'workspace-bot-not-found') {
819
+ return commandResult(sessionBindErrorMessage(error));
820
+ }
821
+ titleQuery = false;
822
+ titleSearchIncomplete = false;
823
+ }
406
824
  }
407
825
  if (!validSessionId(sessionId)) return commandResult(t(SESSION_BIND_USAGE));
408
826
  if (typeof harness?.bindWorkspaceSession !== 'function') {
@@ -412,7 +830,9 @@ async function runSessionBindCommand(command, harness, conversationKey) {
412
830
  return commandResult(t('当前消息缺少可绑定的会话上下文。'));
413
831
  }
414
832
  try {
415
- const bound = await harness.bindWorkspaceSession(conversationKey, sessionId);
833
+ const bound = titleBindingWorkspace
834
+ ? await harness.bindWorkspaceSession(conversationKey, sessionId, { expectedWorkspace: titleBindingWorkspace })
835
+ : await harness.bindWorkspaceSession(conversationKey, sessionId);
416
836
  harness.assertWorkspaceScope?.();
417
837
  const workspace = normalizedWorkspacePath(bound?.workspace);
418
838
  const boundSessionId = safeDisplayText(bound?.sessionId);
@@ -430,10 +850,122 @@ async function runSessionBindCommand(command, harness, conversationKey) {
430
850
  ].join('\n');
431
851
  return commandResult(message, splitWorkspaceCommandMessage(message));
432
852
  } catch (error) {
853
+ // A keyword that did resolve to one Session must not answer with the
854
+ // generic "cannot read this Session" line: name the match it tried, so the
855
+ // reader can retry with its ID instead of guessing which keyword failed.
856
+ if (titleBinding && (error?.code === 'session-summary-unavailable'
857
+ || error?.code === 'session-id-invalid'
858
+ || error?.code === 'session-not-registered'
859
+ || error?.code === 'session-subagent-unsupported'
860
+ || isSessionNotFound(error?.code))) {
861
+ return commandResult(t(SESSION_TITLE_BIND_FAILED, {
862
+ title: titleBinding.title,
863
+ sessionId: titleBinding.sessionId,
864
+ workspace: titleBinding.workspaceLabel,
865
+ }));
866
+ }
867
+ if (titleQuery && (error?.code === 'session-id-invalid'
868
+ || error?.code === 'session-not-registered'
869
+ || isSessionNotFound(error?.code))) {
870
+ return commandResult(t(
871
+ titleSearchIncomplete ? SESSION_TITLE_SEARCH_INCOMPLETE_MISS : SESSION_TITLE_MISS,
872
+ { keyword: sessionId },
873
+ ));
874
+ }
433
875
  return commandResult(sessionBindErrorMessage(error));
434
876
  }
435
877
  }
436
878
 
879
+ /**
880
+ * `/sessionarchive <Session ID | 序号>`: asks the Harness to archive one Session.
881
+ * The bot never archives on its own: it resolves the target, refuses the two
882
+ * cases that would leave this chat in a broken state, and reports what the Host
883
+ * said.
884
+ */
885
+ async function runSessionArchiveCommand(command, harness, conversationKey) {
886
+ const match = SESSION_ARCHIVE_COMMAND.exec(command);
887
+ const target = match?.[1];
888
+ const stopActivity = Boolean(match?.[2]);
889
+ if (!validSessionId(target)) return commandResult(t(SESSION_ARCHIVE_USAGE));
890
+ if (typeof harness?.archiveWorkspaceSession !== 'function'
891
+ || typeof harness?.listWorkspaceSessions !== 'function') {
892
+ return commandResult(t('当前机器人暂不支持归档会话。'));
893
+ }
894
+ try {
895
+ const boundSessionId = boundSessionIdFor(harness, conversationKey);
896
+ let sessionId = target;
897
+ let title = '';
898
+ let archived = false;
899
+
900
+ if (/^\d+$/u.test(target)) {
901
+ const resolved = await resolveSessionListWorkspace('', harness, { conversationKey });
902
+ if (resolved.error) return commandResult(resolved.error);
903
+ const listed = await harness.listWorkspaceSessions(resolved.workspace);
904
+ if (!listed || !Array.isArray(listed.sessions)) {
905
+ throw new TypeError('Harness returned an invalid workspace session list');
906
+ }
907
+ const { live } = splitArchived(listed.sessions);
908
+ const position = Number(target);
909
+ if (!Number.isSafeInteger(position) || position < 1 || position > live.length) {
910
+ return commandResult(t('会话序号不存在,请先执行 /sessionlist 查看序号。'));
911
+ }
912
+ const picked = live[position - 1];
913
+ const pickedId = picked?.sessionId;
914
+ if (!validSessionId(pickedId)) {
915
+ throw new TypeError('Harness returned an invalid session id');
916
+ }
917
+ harness.assertWorkspaceScope?.();
918
+ const preview = [
919
+ t(SESSION_ARCHIVE_PREVIEW, { index: target }),
920
+ t('标题:{title}', { title: safeDisplayText(picked?.title) || t('暂无标题') }),
921
+ t('工作区:{workspace}', { workspace: resolved.workspace }),
922
+ `ID:${pickedId}`,
923
+ t(SESSION_ARCHIVE_PREVIEW_HINT, { sessionId: pickedId }),
924
+ ].join('\n');
925
+ return commandResult(preview, splitWorkspaceCommandMessage(preview));
926
+ } else {
927
+ // Best-effort lookup for a receipt title and the already-archived check;
928
+ // an id no listing shows is still handed to the Host.
929
+ const { paths } = await workspacePathSnapshot(harness, { includeTitles: true });
930
+ for (const workspace of paths) {
931
+ const sessions = await listWorkspaceSessionsOrNull(harness, workspace);
932
+ if (!sessions) continue;
933
+ const found = sessions.find((session) => session?.sessionId === sessionId);
934
+ if (!found) continue;
935
+ title = safeDisplayText(found.title);
936
+ archived = found.archived === true;
937
+ break;
938
+ }
939
+ }
940
+
941
+ harness.assertWorkspaceScope?.();
942
+ if (archived) return commandResult(t('该会话已经归档。'));
943
+ if (boundSessionId && boundSessionId === sessionId) {
944
+ return commandResult(t('这是本对话当前绑定的会话,请先 /new 或绑定其他会话,再归档它。'));
945
+ }
946
+
947
+ await harness.archiveWorkspaceSession(sessionId, { stopActivity });
948
+ harness.assertWorkspaceScope?.();
949
+ const message = [
950
+ t('已归档会话:'),
951
+ t('标题:{title}', { title: title || t('暂无标题') }),
952
+ `ID:${sessionId}`,
953
+ ].join('\n');
954
+ return commandResult(message, splitWorkspaceCommandMessage(message));
955
+ } catch (error) {
956
+ if (error?.code === 'workspace-bot-not-found') {
957
+ return commandResult(t('机器人正在移除或已重新接入,无法归档原会话的会话。'));
958
+ }
959
+ if (error?.code === 'harness-api-not-found') {
960
+ return commandResult(t('当前 DSH 版本不支持通过机器人归档会话。'));
961
+ }
962
+ if (['agent-busy', 'turn-blocked', 'session-archived'].includes(error?.code)) {
963
+ return commandResult(t('该会话仍有任务在运行,请先 /stop,或使用 /sessionarchive <目标> --stop。'));
964
+ }
965
+ return commandResult(t('暂时无法归档该会话,请稍后重试。'));
966
+ }
967
+ }
968
+
437
969
  async function runConversationWorkspaceCommand(command, harness, conversationKey) {
438
970
  if (typeof harness?.currentConversationWorkspace !== 'function') {
439
971
  return commandResult(t('当前机器人暂不支持按对话设置专属工作区。'));
@@ -542,6 +1074,9 @@ export async function runWorkspaceCommand(text, harness, conversationKey) {
542
1074
  if (threadMatch) {
543
1075
  return runConversationWorkspaceCommand(command, harness, conversationKey);
544
1076
  }
1077
+ if (SESSION_ARCHIVE_PREFIX.test(command)) {
1078
+ return runSessionArchiveCommand(command, harness, conversationKey);
1079
+ }
545
1080
  if (SESSION_BIND_PREFIX.test(command)) {
546
1081
  return runSessionBindCommand(command, harness, conversationKey);
547
1082
  }
@@ -584,6 +1119,7 @@ export function isWorkspaceCommand(text) {
584
1119
  if (typeof text !== 'string') return false;
585
1120
  const command = text.trim();
586
1121
  return SESSION_BIND_PREFIX.test(command)
1122
+ || SESSION_ARCHIVE_PREFIX.test(command)
587
1123
  || SESSION_LIST_COMMAND.test(command)
588
1124
  || WORKSPACE_LIST_COMMAND.test(command)
589
1125
  || WORKSPACE_COMMAND.test(command)