@xmanrui/dsh-im 5.6.0 → 5.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.en.md +22 -6
  2. package/README.md +22 -6
  3. package/assets/sponsors/88api.jpg +0 -0
  4. package/lib/client.js +361 -159
  5. package/lib/index.js +323 -321
  6. package/package.json +1 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/delivery-settings.js +13 -0
  11. package/plugin-src/client/i18n-ru.js +18 -0
  12. package/plugin-src/client/i18n.js +18 -0
  13. package/plugin-src/client/session-channel-logos.js +8 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  17. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  18. package/plugin-src/host/delivery-suggestions.mjs +2 -0
  19. package/plugin-src/host/update-service.mjs +44 -13
  20. package/scripts/verify-package.mjs +17 -6
  21. package/src/channels/feishu/bridge.mjs +29 -12
  22. package/src/channels/feishu/feishu-runtime.mjs +13 -1
  23. package/src/channels/feishu/message-utils.mjs +1 -0
  24. package/src/channels/qq/markdown-reply.mjs +5 -2
  25. package/src/channels/qq/qq-bridge.mjs +41 -2
  26. package/src/channels/shared/bot-workspace-store.mjs +248 -0
  27. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  28. package/src/channels/shared/conversation-directory.mjs +29 -0
  29. package/src/channels/shared/harness-client.mjs +72 -2
  30. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  31. package/src/channels/shared/i18n-en/shared-a.mjs +5 -0
  32. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  33. package/src/channels/shared/i18n-ru/shared-a.mjs +5 -0
  34. package/src/channels/shared/message-failure.mjs +8 -0
  35. package/src/channels/shared/new-command.mjs +7 -0
  36. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  37. package/src/channels/shared/text-harness-bridge.mjs +3 -2
  38. package/src/channels/shared/workspace-command.mjs +22 -9
  39. package/src/channels/slack/slack-api.mjs +21 -5
  40. package/src/channels/slack/slack-runtime.mjs +69 -20
  41. package/src/channels/wecom/wecom-controller.mjs +89 -1
@@ -5,6 +5,7 @@ import { randomUUID } from 'node:crypto';
5
5
  import { chunkMarkdownText } from '../shared/markdown-chunks.mjs';
6
6
  import QRCode from 'qrcode';
7
7
  import { waitForFeishuOperation } from './feishu-channel.mjs';
8
+ import { startNewConversation } from '../shared/new-command.mjs';
8
9
  import {
9
10
  conversationKey,
10
11
  conversationScope,
@@ -144,7 +145,7 @@ const WATCH_COMMAND = /^\/watch(?:\s+([^\s]+))?$/i;
144
145
  const UNWATCH_COMMAND = /^\/unwatch(?:\s+([^\s]+))?$/i;
145
146
  const WATCHLIST_COMMAND = /^\/watchlist$/i;
146
147
  const SESSION_LIST_PREFIX = /^\/(?:sessionlist|sessions)(?:\s|$)/i;
147
- const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)$/i;
148
+ const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)(?:\s+all)?$/i;
148
149
  // After the merge a bare /workspace or /ws opens the same picker card.
149
150
  const BARE_WORKSPACE_COMMAND = /^\/(?:workspace|ws)$/i;
150
151
  const NUMBER_REPLY = /^\d{1,2}$/;
@@ -1852,8 +1853,9 @@ export class FeishuHarnessBridge {
1852
1853
  );
1853
1854
  return;
1854
1855
  }
1855
- await this.#state.clearSession(key);
1856
- await this.#send(event.message.chat_id, t('已开启全新 Harness 会话。'), { replyTo: event.message.message_id });
1856
+ await this.#send(event.message.chat_id, await startNewConversation({
1857
+ state: this.#state, harness: this.#harness, key,
1858
+ }), { replyTo: event.message.message_id });
1857
1859
  await this.#sendMenuCard(key, event.message.chat_id, { replyTo: event.message.message_id });
1858
1860
  return;
1859
1861
  }
@@ -1896,8 +1898,12 @@ export class FeishuHarnessBridge {
1896
1898
  );
1897
1899
  return;
1898
1900
  }
1901
+ if (BARE_WORKSPACE_COMMAND.test(commandText)
1902
+ && this.#harness.conversationDirectoryConfig?.()?.enabled === true) return;
1899
1903
  if (BARE_WORKSPACE_COMMAND.test(commandText) || WORKSPACE_LIST_COMMAND.test(commandText)) {
1900
- await this.#showWorkspaces({ chatId: event.message.chat_id, key, replyTo: event.message.message_id });
1904
+ await this.#showWorkspaces({ chatId: event.message.chat_id, key, replyTo: event.message.message_id }, {
1905
+ includeConversationDirectories: /\s+all$/iu.test(commandText),
1906
+ });
1901
1907
  return;
1902
1908
  }
1903
1909
  if (WATCH_COMMAND.test(commandText)) {
@@ -2846,8 +2852,7 @@ export class FeishuHarnessBridge {
2846
2852
  await reply(t('当前任务仍在运行,请先停止任务或等待任务完成后再开启新会话。'));
2847
2853
  return;
2848
2854
  }
2849
- await this.#state.clearSession(key);
2850
- await reply(t('已开启全新 Harness 会话。'));
2855
+ await reply(await startNewConversation({ state: this.#state, harness: this.#harness, key }));
2851
2856
  await this.#sendMenuCard(key, chatId, { updateMessageId: messageId, replyTo: messageId });
2852
2857
  return;
2853
2858
  }
@@ -3021,8 +3026,9 @@ export class FeishuHarnessBridge {
3021
3026
  await this.#send(chatId, message, { replyTo: messageId });
3022
3027
  return;
3023
3028
  }
3029
+ let receipt;
3024
3030
  try {
3025
- await this.#state.clearSession(key);
3031
+ receipt = await startNewConversation({ state: this.#state, harness: this.#harness, key });
3026
3032
  } catch (error) {
3027
3033
  // A persistence error can still leave the in-memory binding cleared.
3028
3034
  await finish('failed', safeErrorText(error));
@@ -3030,7 +3036,7 @@ export class FeishuHarnessBridge {
3030
3036
  }
3031
3037
  await finish('success');
3032
3038
  // A receipt delivery failure must not turn a completed reset into a retry.
3033
- await this.#send(chatId, t('已开启全新 Harness 会话。'), { replyTo: messageId })
3039
+ await this.#send(chatId, receipt, { replyTo: messageId })
3034
3040
  .catch((error) => this.#logger.warn?.('[dsh-feishu] new session receipt failed:', error?.message));
3035
3041
  }
3036
3042
 
@@ -3183,11 +3189,11 @@ export class FeishuHarnessBridge {
3183
3189
  }
3184
3190
  }
3185
3191
 
3186
- async #showWorkspaces({ chatId, key, replyTo = null }, { updateMessageId = null } = {}) {
3192
+ async #showWorkspaces({ chatId, key, replyTo = null }, { updateMessageId = null, includeConversationDirectories = false } = {}) {
3187
3193
  try {
3188
3194
  const { current, paths, titles } = await workspacePathSnapshot(
3189
3195
  this.#harness,
3190
- { signal: this.#cardDataSignal(), includeTitles: true },
3196
+ { signal: this.#cardDataSignal(), includeTitles: true, includeConversationDirectories },
3191
3197
  );
3192
3198
  this.#rememberMenu(key, { kind: 'workspaces', paths });
3193
3199
  await this.#sendCard(
@@ -5385,10 +5391,15 @@ export class FeishuHarnessBridge {
5385
5391
 
5386
5392
  async #preparePrompt(event, key, message) {
5387
5393
  const snapshot = this.#acceptedMessageIds.get(event.message.message_id);
5394
+ const originalFiles = Array.isArray(message.files) ? [...message.files] : [];
5388
5395
  const build = async (input) => {
5389
5396
  const rich = hasInboundImages(input) || hasReplyReference(input);
5390
5397
  const original = rich
5391
- ? await promptContentForInboundMessage(input, { signal: this.#signal, deferImages: true })
5398
+ ? await promptContentForInboundMessage(input, {
5399
+ signal: this.#signal,
5400
+ deferImages: true,
5401
+ originalFiles,
5402
+ })
5392
5403
  : input.content;
5393
5404
  const enhanced = enhanceContextContent(original, snapshot, () => ({
5394
5405
  channel: 'feishu',
@@ -5410,7 +5421,12 @@ export class FeishuHarnessBridge {
5410
5421
  && (nonEmptyString(message.content) || hasInboundImages(message) || hasInboundFiles(message));
5411
5422
  if (!topicAnchor) return build(message);
5412
5423
 
5413
- const withoutAnchor = { ...message };
5424
+ // Keep the temporary topic-root copy connected to the final request's
5425
+ // attachment array. Reply resolution may append lazy files to it.
5426
+ const withoutAnchor = {
5427
+ ...message,
5428
+ files: Array.isArray(message.files) ? message.files : (message.files = []),
5429
+ };
5414
5430
  delete withoutAnchor.replyTo;
5415
5431
  const base = await build(withoutAnchor);
5416
5432
  let preparedSessionId;
@@ -5426,6 +5442,7 @@ export class FeishuHarnessBridge {
5426
5442
  }
5427
5443
  const prepared = await build({
5428
5444
  ...message,
5445
+ files: message.files,
5429
5446
  replyTo: {
5430
5447
  ...message.replyTo,
5431
5448
  load: async (options) => {
@@ -948,7 +948,19 @@ export class FeishuRuntime {
948
948
  wsClient?.close({ force: true });
949
949
  const bridge = this.#bridge;
950
950
  this.#bridge = null;
951
- if (bridge) await bridge.waitForIdle();
951
+ let timer;
952
+ try {
953
+ const idle = await Promise.race([
954
+ (bridge?.waitForIdle() ?? Promise.resolve()).then(() => true),
955
+ new Promise((resolve) => {
956
+ timer = setTimeout(() => resolve(false), 2_000);
957
+ timer.unref?.();
958
+ }),
959
+ ]);
960
+ if (!idle) this.#logger.warn?.('[dsh-feishu] bridge idle wait timed out after 2000ms; continuing cleanup');
961
+ } finally {
962
+ clearTimeout(timer);
963
+ }
952
964
  this.#client = null;
953
965
  this.#status.feishuLongConnectionState = preserveError ? 'failed' : 'idle';
954
966
  this.#status.slashCommandRegistration = 'idle';
@@ -549,6 +549,7 @@ function feishuReplyReference(event, client) {
549
549
  : {}),
550
550
  ...(content ? { content } : {}),
551
551
  attachments,
552
+ ...(quoted.files?.length ? { files: quoted.files } : {}),
552
553
  ...(messageType === 'interactive' && !content && attachments.length === 0
553
554
  ? { unavailableReason: 'unsupported' }
554
555
  : {}),
@@ -42,11 +42,14 @@ function sendPlainText(bot, target, content, msgSeq) {
42
42
  * 以 markdown(msg_type=2)发送回复;单条被平台拒绝时回退纯文本(msg_type=0)。
43
43
  * 返回每条消息的平台响应,供调用方提取 provider message ids。
44
44
  */
45
- export async function sendMarkdownReply(bot, target, text, { logger, signal, requireComplete = false } = {}) {
45
+ export async function sendMarkdownReply(bot, target, text, { logger, signal, requireComplete = false, passiveRepliesUsed = 0 } = {}) {
46
46
  const chunks = chunkMarkdownParts(text);
47
47
  const results = [];
48
48
  const firstMsgSeq = nextMsgSeq();
49
- const passiveLimit = target?.msgId ? PASSIVE_REPLY_LIMIT[target.scope] : null;
49
+ // Earlier replies to the same msg_id (for example a timeout notice) spend
50
+ // part of QQ's passive budget; at least one slot is kept for this reply.
51
+ const passiveLimit = target?.msgId
52
+ ? Math.max(1, PASSIVE_REPLY_LIMIT[target.scope] - passiveRepliesUsed) : null;
50
53
  const overflow = passiveLimit !== null && chunks.length > passiveLimit;
51
54
  const passiveContentCount = overflow ? passiveLimit - 1 : chunks.length;
52
55
  const proactiveTarget = target?.msgId
@@ -71,6 +71,7 @@ import {
71
71
  COMMAND_PERMISSION_DENIED_MESSAGE,
72
72
  evaluateInboundAccess,
73
73
  } from '../shared/inbound-access.mjs';
74
+ import { ApiError } from '@tencent-connect/qqbot-nodejs';
74
75
  import { sendMarkdownReply } from './markdown-reply.mjs';
75
76
  import {
76
77
  isQqMenuCommand, parseQqMenuCommand, QqMenuStore,
@@ -269,6 +270,28 @@ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
269
270
  };
270
271
  }
271
272
 
273
+ // QQ accepts passive replies to an inbound msg_id for a bounded window
274
+ // (C2C 60 min, group 5 min). Proactive C2C/group sends are quota-limited and
275
+ // are often refused, so a late result keeps the passive route while the
276
+ // window is still open and only falls back to proactive delivery after it.
277
+ const PASSIVE_REPLY_WINDOW_MS = Object.freeze({ c2c: 60 * 60_000, group: 5 * 60_000 });
278
+ const PASSIVE_REPLY_MARGIN_MS = 30_000;
279
+
280
+ function deferredQqTarget(message, target, acceptedAt) {
281
+ const route = { scope: target.scope, targetId: target.targetId };
282
+ const msgId = nonEmptyString(target.msgId);
283
+ if (!msgId || !PASSIVE_REPLY_WINDOW_MS[target.scope]) return route;
284
+ const sentAt = Date.parse(message?.timestamp ?? '');
285
+ return { ...route, msgId, receivedAt: Number.isFinite(sentAt) ? Math.min(sentAt, acceptedAt) : acceptedAt };
286
+ }
287
+
288
+ export function deferredDeliveryTarget(target, now = Date.now()) {
289
+ const route = { scope: target?.scope, targetId: target?.targetId };
290
+ const window = PASSIVE_REPLY_WINDOW_MS[target?.scope];
291
+ if (!nonEmptyString(target?.msgId) || !window || !Number.isFinite(target?.receivedAt)) return route;
292
+ return now - target.receivedAt < window - PASSIVE_REPLY_MARGIN_MS ? { ...route, msgId: target.msgId } : route;
293
+ }
294
+
272
295
  function nonEmptyString(value) {
273
296
  return typeof value === 'string' && value.trim() ? value.trim() : null;
274
297
  }
@@ -896,7 +919,22 @@ export class QqHarnessBridge {
896
919
  }
897
920
 
898
921
  async #deliverDeferredOutcome(entry, outcome) {
899
- await sendMarkdownReply(this.#bot, entry.target, deferredOutcomeText(outcome), { logger: this.#logger });
922
+ const text = deferredOutcomeText(outcome);
923
+ const target = deferredDeliveryTarget(entry.target);
924
+ if (!target.msgId) {
925
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger });
926
+ return true;
927
+ }
928
+ try {
929
+ // The timeout notice already answered this msg_id once.
930
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger, passiveRepliesUsed: 1 });
931
+ } catch (error) {
932
+ // Nothing was sent and QQ definitely refused the passive reply (window
933
+ // closed early or budget spent), so the proactive route cannot duplicate it.
934
+ if (!(error instanceof ApiError) || !(error.httpStatus >= 400 && error.httpStatus < 500)) throw error;
935
+ this.#logger.warn?.('[dsh-im:qq] passive deferred reply was refused; retrying proactively:', error);
936
+ await sendMarkdownReply(this.#bot, { scope: target.scope, targetId: target.targetId }, text, { logger: this.#logger });
937
+ }
900
938
  return true;
901
939
  }
902
940
 
@@ -1155,6 +1193,7 @@ export class QqHarnessBridge {
1155
1193
  batchSubmission = null,
1156
1194
  } = {}) {
1157
1195
  if (this.#signal?.aborted) return;
1196
+ const acceptedAt = Date.now();
1158
1197
  const messageId = nonEmptyString(message?.messageId);
1159
1198
  const sender = nonEmptyString(message?.senderId);
1160
1199
  if (!messageId || !sender || message.senderIsBot === true) return;
@@ -1273,7 +1312,7 @@ export class QqHarnessBridge {
1273
1312
  await this.#markPendingSubmitted(key, messageId);
1274
1313
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
1275
1314
  onNotice: (notice) => this.#bot.sendText(target, notice),
1276
- deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1315
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: deferredQqTarget(message, target, acceptedAt) }),
1277
1316
  harness: this.#harness,
1278
1317
  state: this.#state,
1279
1318
  key,
@@ -38,6 +38,13 @@ import {
38
38
  } from './model-setting.mjs';
39
39
  import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
40
40
  import { configValidationError, withConfigResource } from './config-read-error.mjs';
41
+ import {
42
+ DEFAULT_CONVERSATION_DIRECTORY,
43
+ normalizeConversationDirectory,
44
+ validateConversationDirectory,
45
+ workspaceManualEditDisabled,
46
+ } from './conversation-directory.mjs';
47
+ import { conversationDirectoryName, prepareDirectoryPath } from './conversation-directory-ensure.mjs';
41
48
 
42
49
  const DELIVERY_DOCUMENT_VERSION = 2;
43
50
  const SESSION_SYNC_DOCUMENT_VERSION = 3;
@@ -134,6 +141,42 @@ function normalizeConversationWorkspaces(value) {
134
141
  return conversationWorkspaces;
135
142
  }
136
143
 
144
+ function normalizeConversationDirectoryOverrides(value) {
145
+ const result = Object.create(null);
146
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return result;
147
+ for (const [botId, config] of Object.entries(value)) {
148
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) continue;
149
+ const normalized = normalizeConversationDirectory(config);
150
+ if (normalized) result[botId] = normalized;
151
+ }
152
+ return result;
153
+ }
154
+
155
+ function normalizeSessionDirectories(value) {
156
+ const result = Object.create(null);
157
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return result;
158
+ for (const [botId, entries] of Object.entries(value)) {
159
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId) || !entries || typeof entries !== 'object') continue;
160
+ const normalized = Object.create(null);
161
+ for (const [key, record] of Object.entries(entries)) {
162
+ if (!record || typeof record !== 'object' || typeof record.base !== 'string'
163
+ || typeof record.workspace !== 'string' || !isAbsolute(record.base) || !isAbsolute(record.workspace)) continue;
164
+ const config = normalizeConversationDirectory({ enabled: true, strategy: record.strategy, prefix: record.prefix });
165
+ if (config) normalized[key] = {
166
+ base: resolve(record.base), workspace: resolve(record.workspace), ...config,
167
+ timestamp: Number.isSafeInteger(record.timestamp) && record.timestamp > 0
168
+ ? record.timestamp : undefined,
169
+ pending: record.pending === true,
170
+ history: Array.isArray(record.history)
171
+ ? [...new Set(record.history.filter((path) => typeof path === 'string' && isAbsolute(path)).map((path) => resolve(path)))]
172
+ : [],
173
+ };
174
+ }
175
+ if (Object.keys(normalized).length) result[botId] = normalized;
176
+ }
177
+ return result;
178
+ }
179
+
137
180
  function normalizeDeliveryTarget(value, { targetId, allowSessionSync = false } = {}) {
138
181
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
139
182
  throw deliveryTargetError('invalid-target', 'Invalid delivery target');
@@ -340,6 +383,9 @@ function normalizeDocument(value) {
340
383
  }
341
384
  }
342
385
  const accessPolicies = normalizeAccessPolicies(value.accessPolicies, workspaces);
386
+ const conversationDirectory = normalizeConversationDirectory(value.conversationDirectory);
387
+ const conversationDirectories = normalizeConversationDirectoryOverrides(value.conversationDirectories);
388
+ const sessionDirectories = normalizeSessionDirectories(value.sessionDirectories);
343
389
  const version = Math.max(
344
390
  value.version,
345
391
  value.accessPolicies === undefined ? 1 : DELIVERY_DOCUMENT_VERSION,
@@ -350,6 +396,9 @@ function normalizeDocument(value) {
350
396
  version,
351
397
  workspaces,
352
398
  conversationWorkspaces,
399
+ conversationDirectory,
400
+ conversationDirectories,
401
+ sessionDirectories,
353
402
  agentPresets,
354
403
  models,
355
404
  contextEnhancement,
@@ -365,6 +414,9 @@ function storedDocument({
365
414
  version,
366
415
  workspaces,
367
416
  conversationWorkspaces,
417
+ conversationDirectory,
418
+ conversationDirectories,
419
+ sessionDirectories,
368
420
  agentPresets,
369
421
  models,
370
422
  contextEnhancement,
@@ -375,6 +427,9 @@ function storedDocument({
375
427
  busyMessageModes,
376
428
  }) {
377
429
  const document = { version, workspaces };
430
+ if (conversationDirectory) document.conversationDirectory = conversationDirectory;
431
+ if (Object.keys(conversationDirectories).length) document.conversationDirectories = conversationDirectories;
432
+ if (Object.keys(sessionDirectories).length) document.sessionDirectories = sessionDirectories;
378
433
  if (Object.keys(dsBotBindings).length > 0) document.dsBotBindings = dsBotBindings;
379
434
  if (Object.keys(busyMessageModes).length > 0) document.busyMessageModes = busyMessageModes;
380
435
  if (Object.keys(aliases).length > 0) document.aliases = aliases;
@@ -444,6 +499,9 @@ export class BotWorkspaceStore {
444
499
  #dsBotBindings = Object.create(null);
445
500
  #accessPolicies = Object.create(null);
446
501
  #conversationWorkspaces = Object.create(null);
502
+ #conversationDirectory = null;
503
+ #conversationDirectories = Object.create(null);
504
+ #sessionDirectories = Object.create(null);
447
505
  #generations = new Map();
448
506
  #nextGeneration = 1;
449
507
  #conversationGenerations = new Map();
@@ -477,6 +535,9 @@ export class BotWorkspaceStore {
477
535
  this.#dsBotBindings = normalized.dsBotBindings;
478
536
  this.#accessPolicies = normalized.accessPolicies;
479
537
  this.#conversationWorkspaces = normalized.conversationWorkspaces;
538
+ this.#conversationDirectory = normalized.conversationDirectory;
539
+ this.#conversationDirectories = normalized.conversationDirectories;
540
+ this.#sessionDirectories = normalized.sessionDirectories;
480
541
  } catch (error) {
481
542
  if (error?.code !== 'ENOENT') throw withConfigResource(error, 'workspace-config');
482
543
  this.#version = 1;
@@ -490,6 +551,9 @@ export class BotWorkspaceStore {
490
551
  this.#dsBotBindings = Object.create(null);
491
552
  this.#accessPolicies = Object.create(null);
492
553
  this.#conversationWorkspaces = Object.create(null);
554
+ this.#conversationDirectory = null;
555
+ this.#conversationDirectories = Object.create(null);
556
+ this.#sessionDirectories = Object.create(null);
493
557
  }
494
558
  this.#generations.clear();
495
559
  this.#nextGeneration = 1;
@@ -525,6 +589,112 @@ export class BotWorkspaceStore {
525
589
  return this.#workspaces[botIdOf(botId)] ?? this.#defaultWorkspace;
526
590
  }
527
591
 
592
+ conversationDirectoryFor(botId) {
593
+ const id = botIdOf(botId);
594
+ return { ...(Object.hasOwn(this.#conversationDirectories, id)
595
+ ? this.#conversationDirectories[id]
596
+ : this.#conversationDirectory ?? DEFAULT_CONVERSATION_DIRECTORY) };
597
+ }
598
+
599
+ conversationDirectoryOverrideFor(botId) {
600
+ const id = botIdOf(botId);
601
+ return Object.hasOwn(this.#conversationDirectories, id)
602
+ ? { ...this.#conversationDirectories[id] } : null;
603
+ }
604
+
605
+ async setConversationDirectory(botId, config, { incarnation } = {}) {
606
+ const id = botId === null ? null : botIdOf(botId);
607
+ const normalized = config === null ? null : validateConversationDirectory(config);
608
+ return this.#enqueue(id ?? '__channel__', async () => {
609
+ if (id !== null && (!this.has(id)
610
+ || (incarnation !== undefined && incarnation !== this.incarnationFor(id)))) {
611
+ const error = new Error('找不到要修改的机器人。');
612
+ error.code = 'workspace-bot-not-found';
613
+ throw error;
614
+ }
615
+ const previousDefault = this.#conversationDirectory;
616
+ const previousOverrides = { ...this.#conversationDirectories };
617
+ if (id === null) this.#conversationDirectory = normalized;
618
+ else if (normalized === null) delete this.#conversationDirectories[id];
619
+ else this.#conversationDirectories[id] = normalized;
620
+ try { await this.#persist(); }
621
+ catch (error) {
622
+ this.#conversationDirectory = previousDefault;
623
+ this.#conversationDirectories = previousOverrides;
624
+ throw error;
625
+ }
626
+ });
627
+ }
628
+
629
+ conversationDirectoryPathsFor(botId) {
630
+ return [...new Set(Object.values(this.#sessionDirectories[botIdOf(botId)] ?? {})
631
+ .flatMap((entry) => [entry.workspace, ...(entry.history ?? [])]))];
632
+ }
633
+
634
+ async prepareConversationDirectory(botId, conversationKey, {
635
+ explicitNew = false, incarnation, clearSession, onConversationGeneration,
636
+ } = {}) {
637
+ const id = botIdOf(botId);
638
+ if (!this.has(id) || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
639
+ const error = new Error('找不到要修改的机器人。');
640
+ error.code = 'workspace-bot-not-found';
641
+ throw error;
642
+ }
643
+ const config = this.conversationDirectoryFor(id);
644
+ if (!config.enabled) return null;
645
+ return this.#enqueue(id, async () => {
646
+ const existing = this.#sessionDirectories[id]?.[conversationKey];
647
+ const current = this.conversationWorkspaceFor(id, conversationKey);
648
+ const records = Object.values(this.#sessionDirectories[id] ?? {});
649
+ let base = existing?.base ?? current;
650
+ const visited = new Set();
651
+ while (!visited.has(base)) {
652
+ visited.add(base);
653
+ const parent = records.find((record) => record.workspace === base
654
+ || record.history?.includes(base))?.base;
655
+ if (!parent || parent === base) break;
656
+ base = parent;
657
+ }
658
+ const sameConfig = existing?.workspace === current && existing?.base === base
659
+ && existing?.strategy === config.strategy && existing?.prefix === config.prefix;
660
+ const reuse = sameConfig && (config.strategy === 'per-conversation'
661
+ || (!explicitNew && existing?.pending));
662
+ const timestamp = reuse ? existing.timestamp : Date.now();
663
+ const workspace = reuse ? existing.workspace : resolve(base, conversationDirectoryName(conversationKey, config, timestamp, `${this.#path}:${id}`));
664
+ try { await prepareDirectoryPath(base, workspace); }
665
+ catch (error) {
666
+ console.warn('[dsh-im] conversation directory preparation failed:', error?.message ?? error);
667
+ return { warning: '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。' };
668
+ }
669
+ const entries = { ...(this.#sessionDirectories[id] ?? {}), [conversationKey]: {
670
+ base, workspace, ...config, timestamp, pending: explicitNew,
671
+ history: existing && existing.workspace !== workspace
672
+ ? [...new Set([...(existing.history ?? []), existing.workspace])]
673
+ : existing?.history ?? [],
674
+ } };
675
+ const previousRecords = this.#sessionDirectories[id];
676
+ const previousOverrides = this.#conversationWorkspaces[id];
677
+ if (workspace !== current) {
678
+ const generation = this.publishConversationWorkspaceSwitch(id, conversationKey);
679
+ onConversationGeneration?.(generation);
680
+ await clearSession?.(conversationKey);
681
+ }
682
+ this.#sessionDirectories[id] = entries;
683
+ const overrides = { ...(this.#conversationWorkspaces[id] ?? {}), [conversationKey]: workspace };
684
+ this.#conversationWorkspaces[id] = overrides;
685
+ try { await this.#persist(); }
686
+ catch (error) {
687
+ if (previousRecords) this.#sessionDirectories[id] = previousRecords;
688
+ else delete this.#sessionDirectories[id];
689
+ if (previousOverrides) this.#conversationWorkspaces[id] = previousOverrides;
690
+ else delete this.#conversationWorkspaces[id];
691
+ console.warn('[dsh-im] conversation directory switch failed:', error?.message ?? error);
692
+ return { warning: '会话目录未生效:无法切换目录;本次仍在原工作区运行。' };
693
+ }
694
+ return { workspace };
695
+ });
696
+ }
697
+
528
698
  /**
529
699
  * An explicit override is stored even when it equals the current bot default,
530
700
  * so a later default change must never move a conversation that pinned its
@@ -842,6 +1012,7 @@ export class BotWorkspaceStore {
842
1012
 
843
1013
  async setWorkspace(botId, value, { clearSessions, incarnation } = {}) {
844
1014
  const id = botIdOf(botId);
1015
+ if (this.conversationDirectoryFor(id).enabled) throw workspaceManualEditDisabled();
845
1016
  if (!this.has(id)
846
1017
  || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
847
1018
  const error = new Error('找不到要修改的机器人。');
@@ -881,6 +1052,7 @@ export class BotWorkspaceStore {
881
1052
  incarnation,
882
1053
  } = {}) {
883
1054
  const id = botIdOf(botId);
1055
+ if (this.conversationDirectoryFor(id).enabled) throw workspaceManualEditDisabled();
884
1056
  if (typeof conversationKey !== 'string' || !conversationKey
885
1057
  || conversationKey.length > 1_024 || conversationKey.trim() !== conversationKey
886
1058
  || /[\u0000-\u001f\u007f]/u.test(conversationKey)) {
@@ -1199,6 +1371,10 @@ export class BotWorkspaceStore {
1199
1371
  const workspace = await canonicalWorkspacePath(await validateWorkspacePath(value, {
1200
1372
  ungroupedWorkspace: this.#ungroupedWorkspace,
1201
1373
  }));
1374
+ if (this.conversationDirectoryFor(id).enabled
1375
+ && !(await sameWorkspacePath(workspace, this.conversationWorkspaceFor(id, conversationKey)))) {
1376
+ throw workspaceManualEditDisabled();
1377
+ }
1202
1378
  return this.#enqueue(id, async () => {
1203
1379
  if (!this.has(id)
1204
1380
  || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
@@ -1216,6 +1392,19 @@ export class BotWorkspaceStore {
1216
1392
  // workspace switch queued while the session was being adopted must not be
1217
1393
  // silently overwritten by the binding that started before it.
1218
1394
  assertConversationCurrent();
1395
+ if (this.conversationDirectoryFor(id).enabled) {
1396
+ if (!(await sameWorkspacePath(workspace, this.conversationWorkspaceFor(id, conversationKey)))) {
1397
+ throw workspaceManualEditDisabled();
1398
+ }
1399
+ assertConversationCurrent();
1400
+ await setSession(conversationKey, sessionId);
1401
+ assertConversationCurrent();
1402
+ return {
1403
+ workspace, sessionId,
1404
+ generation: this.#generations.get(id),
1405
+ conversationGeneration,
1406
+ };
1407
+ }
1219
1408
  const sameWorkspace = await sameWorkspacePath(workspace, this.workspaceFor(id));
1220
1409
  const previousOverrides = this.#conversationWorkspaces[id];
1221
1410
  const override = previousOverrides?.[conversationKey];
@@ -1371,6 +1560,8 @@ export class BotWorkspaceStore {
1371
1560
  ...Object.keys(this.#deliveryTargets),
1372
1561
  ...Object.keys(this.#accessPolicies),
1373
1562
  ...Object.keys(this.#conversationWorkspaces),
1563
+ ...Object.keys(this.#conversationDirectories),
1564
+ ...Object.keys(this.#sessionDirectories),
1374
1565
  ...this.#dirtyRemovals,
1375
1566
  ]);
1376
1567
  for (const botId of candidates) {
@@ -1382,11 +1573,14 @@ export class BotWorkspaceStore {
1382
1573
  if (!status || typeof status !== 'object' || !Array.isArray(status.bots)) return status;
1383
1574
  return {
1384
1575
  ...status,
1576
+ conversationDirectory: this.#conversationDirectory ? { ...this.#conversationDirectory } : null,
1385
1577
  bots: status.bots.map((bot) => bot?.botId
1386
1578
  ? {
1387
1579
  ...bot,
1388
1580
  ...(this.aliasFor(bot.botId) ? { bot: withBotAlias(bot.bot, this.aliasFor(bot.botId)) } : {}),
1389
1581
  workspace: this.workspaceFor(bot.botId),
1582
+ conversationDirectory: this.conversationDirectoryFor(bot.botId),
1583
+ conversationDirectoryOverride: this.conversationDirectoryOverrideFor(bot.botId),
1390
1584
  agentPreset: this.agentPresetFor(bot.botId),
1391
1585
  model: this.modelFor(bot.botId),
1392
1586
  contextEnhancement: this.contextEnhancementFor(bot.botId),
@@ -1435,8 +1629,10 @@ export class BotWorkspaceStore {
1435
1629
  const hadDsBotBindings = Object.hasOwn(this.#dsBotBindings, id);
1436
1630
  const hadAccessPolicy = Object.hasOwn(this.#accessPolicies, id);
1437
1631
  const hadConversationWorkspaces = Object.hasOwn(this.#conversationWorkspaces, id);
1632
+ const hadDirectoryRecords = Object.hasOwn(this.#conversationDirectories, id) || Object.hasOwn(this.#sessionDirectories, id);
1438
1633
  const needsCleanup = hadWorkspace || hadPreset || hadModel || hadAlias || hadContextEnhancement
1439
1634
  || hadDeliveryTargets || hadDsBotBindings || hadAccessPolicy || hadConversationWorkspaces || hadMessageMode
1635
+ || hadDirectoryRecords
1440
1636
  || this.#dirtyRemovals.has(id);
1441
1637
  delete this.#workspaces[id];
1442
1638
  delete this.#agentPresets[id];
@@ -1448,6 +1644,8 @@ export class BotWorkspaceStore {
1448
1644
  delete this.#dsBotBindings[id];
1449
1645
  delete this.#accessPolicies[id];
1450
1646
  delete this.#conversationWorkspaces[id];
1647
+ delete this.#conversationDirectories[id];
1648
+ delete this.#sessionDirectories[id];
1451
1649
  this.#generations.delete(id);
1452
1650
  this.#incarnations.delete(id);
1453
1651
  if (!needsCleanup) return {
@@ -1486,6 +1684,9 @@ export class BotWorkspaceStore {
1486
1684
  conversationWorkspaces = this.#conversationWorkspaces,
1487
1685
  busyMessageModes = this.#busyMessageModes,
1488
1686
  dsBotBindings = this.#dsBotBindings,
1687
+ conversationDirectory = this.#conversationDirectory,
1688
+ conversationDirectories = this.#conversationDirectories,
1689
+ sessionDirectories = this.#sessionDirectories,
1489
1690
  ) {
1490
1691
  await writeStoredDocument(this.#path, storedDocument({
1491
1692
  version,
@@ -1499,6 +1700,9 @@ export class BotWorkspaceStore {
1499
1700
  accessPolicies,
1500
1701
  aliases,
1501
1702
  busyMessageModes,
1703
+ conversationDirectory,
1704
+ conversationDirectories,
1705
+ sessionDirectories,
1502
1706
  }));
1503
1707
  this.#dirtyRemovals.clear();
1504
1708
  }
@@ -1885,6 +2089,9 @@ export function createBotWorkspaceScope(
1885
2089
  }
1886
2090
  if (property === 'switchWorkspace') {
1887
2091
  return (workspace) => {
2092
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2093
+ return Promise.reject(workspaceManualEditDisabled());
2094
+ }
1888
2095
  if (workspaces.listDsBotBindings(botId).length > 0) {
1889
2096
  throw deliveryTargetError('ds-bot-bound', '请先解除 DS Bot 绑定,再切换机器人工作目录。');
1890
2097
  }
@@ -1926,8 +2133,32 @@ export function createBotWorkspaceScope(
1926
2133
  // bind and the send so a late switch cannot be outrun.
1927
2134
  return (conversationKey) => currentConversationGeneration(conversationKey);
1928
2135
  }
2136
+ if (property === 'conversationDirectoryConfig') {
2137
+ return () => workspaces.conversationDirectoryFor(botId);
2138
+ }
2139
+ if (property === 'conversationDirectoryPaths') {
2140
+ return () => workspaces.conversationDirectoryPathsFor(botId);
2141
+ }
2142
+ if (property === 'prepareConversationDirectory') {
2143
+ return async (conversationKey, options = {}) => {
2144
+ assertCurrentBotScope(isCurrentScope);
2145
+ assertNoDsBinding(conversationKey);
2146
+ const pending = pendingConversationSwitches.get(conversationKey);
2147
+ if (pending) await pending;
2148
+ assertCurrentBotScope(isCurrentScope);
2149
+ return trackConversationSwitch(conversationKey, workspaces.prepareConversationDirectory(botId, conversationKey, {
2150
+ ...options,
2151
+ incarnation,
2152
+ clearSession: (key) => state.clearSession(key),
2153
+ onConversationGeneration: (generation) => maskConversationSwitch(conversationKey, generation),
2154
+ }));
2155
+ };
2156
+ }
1929
2157
  if (property === 'switchConversationWorkspace') {
1930
2158
  return (conversationKey, workspace) => {
2159
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2160
+ return Promise.reject(workspaceManualEditDisabled());
2161
+ }
1931
2162
  assertNoDsBinding(conversationKey);
1932
2163
  if (!isCurrentScope()) {
1933
2164
  const error = new Error('找不到要修改的机器人。');
@@ -1950,6 +2181,9 @@ export function createBotWorkspaceScope(
1950
2181
  }
1951
2182
  if (property === 'clearConversationWorkspace') {
1952
2183
  return (conversationKey) => {
2184
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2185
+ return Promise.reject(workspaceManualEditDisabled());
2186
+ }
1953
2187
  assertNoDsBinding(conversationKey);
1954
2188
  if (!isCurrentScope()) {
1955
2189
  const error = new Error('找不到要修改的机器人。');
@@ -2046,6 +2280,10 @@ export function createBotWorkspaceScope(
2046
2280
  return async (options = {}) => {
2047
2281
  const { inheritBotModel = true, conversationKey, ...createOptions } = options;
2048
2282
  assertNoDsBinding(conversationKey);
2283
+ if (conversationKey) {
2284
+ const prepared = await scopedHarness.prepareConversationDirectory(conversationKey);
2285
+ if (prepared?.workspace) createOptions.workspace = prepared.workspace;
2286
+ }
2049
2287
  // /conv publishes its generation before path validation enters the
2050
2288
  // bot queue. Wait for both phases before pairing a workspace with its
2051
2289
  // generation; otherwise a new session can carry a new fence but old cwd.
@@ -2561,6 +2799,16 @@ export function createWorkspaceAwareController(controller, {
2561
2799
 
2562
2800
  return new Proxy(controller, {
2563
2801
  get(target, property) {
2802
+ if (property === 'updateConversationDirectory') {
2803
+ return async (botId, config) => {
2804
+ await workspaces.setConversationDirectory(
2805
+ botId,
2806
+ config,
2807
+ botId === null ? {} : { incarnation: workspaces.incarnationFor(botId) },
2808
+ );
2809
+ return decorate(await controller.status());
2810
+ };
2811
+ }
2564
2812
  if (property === 'updateWorkspace') return updateWorkspace;
2565
2813
  if (property === 'updateAgentPreset') return updateAgentPreset;
2566
2814
  if (property === 'updateModel') return updateModel;