@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
@@ -1,3 +1,4 @@
1
+ import { ensurePresetWorkspace } from './preset-workspaces.mjs';
1
2
  import { t } from './i18n.mjs';
2
3
  import { normalizeBusyMessageMode, validateBusyMessageMode } from './message-mode.mjs';
3
4
  import { atConnectionStage, connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
@@ -12,10 +13,11 @@ import {
12
13
  unlink,
13
14
  writeFile,
14
15
  } from 'node:fs/promises';
15
- import { dirname, isAbsolute, resolve } from 'node:path';
16
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
16
17
 
17
18
  import {
18
19
  normalizeAgentPresetCatalog,
20
+ normalizeAgentPresetId,
19
21
  validateAgentPresetId,
20
22
  } from './agent-preset.mjs';
21
23
  import {
@@ -38,6 +40,13 @@ import {
38
40
  } from './model-setting.mjs';
39
41
  import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
40
42
  import { configValidationError, withConfigResource } from './config-read-error.mjs';
43
+ import {
44
+ DEFAULT_CONVERSATION_DIRECTORY,
45
+ normalizeConversationDirectory,
46
+ validateConversationDirectory,
47
+ workspaceManualEditDisabled,
48
+ } from './conversation-directory.mjs';
49
+ import { conversationDirectoryName, prepareDirectoryPath } from './conversation-directory-ensure.mjs';
41
50
 
42
51
  const DELIVERY_DOCUMENT_VERSION = 2;
43
52
  const SESSION_SYNC_DOCUMENT_VERSION = 3;
@@ -134,6 +143,42 @@ function normalizeConversationWorkspaces(value) {
134
143
  return conversationWorkspaces;
135
144
  }
136
145
 
146
+ function normalizeConversationDirectoryOverrides(value) {
147
+ const result = Object.create(null);
148
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return result;
149
+ for (const [botId, config] of Object.entries(value)) {
150
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) continue;
151
+ const normalized = normalizeConversationDirectory(config);
152
+ if (normalized) result[botId] = normalized;
153
+ }
154
+ return result;
155
+ }
156
+
157
+ function normalizeSessionDirectories(value) {
158
+ const result = Object.create(null);
159
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return result;
160
+ for (const [botId, entries] of Object.entries(value)) {
161
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId) || !entries || typeof entries !== 'object') continue;
162
+ const normalized = Object.create(null);
163
+ for (const [key, record] of Object.entries(entries)) {
164
+ if (!record || typeof record !== 'object' || typeof record.base !== 'string'
165
+ || typeof record.workspace !== 'string' || !isAbsolute(record.base) || !isAbsolute(record.workspace)) continue;
166
+ const config = normalizeConversationDirectory({ enabled: true, strategy: record.strategy, prefix: record.prefix });
167
+ if (config) normalized[key] = {
168
+ base: resolve(record.base), workspace: resolve(record.workspace), ...config,
169
+ timestamp: Number.isSafeInteger(record.timestamp) && record.timestamp > 0
170
+ ? record.timestamp : undefined,
171
+ pending: record.pending === true,
172
+ history: Array.isArray(record.history)
173
+ ? [...new Set(record.history.filter((path) => typeof path === 'string' && isAbsolute(path)).map((path) => resolve(path)))]
174
+ : [],
175
+ };
176
+ }
177
+ if (Object.keys(normalized).length) result[botId] = normalized;
178
+ }
179
+ return result;
180
+ }
181
+
137
182
  function normalizeDeliveryTarget(value, { targetId, allowSessionSync = false } = {}) {
138
183
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
139
184
  throw deliveryTargetError('invalid-target', 'Invalid delivery target');
@@ -340,6 +385,9 @@ function normalizeDocument(value) {
340
385
  }
341
386
  }
342
387
  const accessPolicies = normalizeAccessPolicies(value.accessPolicies, workspaces);
388
+ const conversationDirectory = normalizeConversationDirectory(value.conversationDirectory);
389
+ const conversationDirectories = normalizeConversationDirectoryOverrides(value.conversationDirectories);
390
+ const sessionDirectories = normalizeSessionDirectories(value.sessionDirectories);
343
391
  const version = Math.max(
344
392
  value.version,
345
393
  value.accessPolicies === undefined ? 1 : DELIVERY_DOCUMENT_VERSION,
@@ -350,6 +398,9 @@ function normalizeDocument(value) {
350
398
  version,
351
399
  workspaces,
352
400
  conversationWorkspaces,
401
+ conversationDirectory,
402
+ conversationDirectories,
403
+ sessionDirectories,
353
404
  agentPresets,
354
405
  models,
355
406
  contextEnhancement,
@@ -365,6 +416,9 @@ function storedDocument({
365
416
  version,
366
417
  workspaces,
367
418
  conversationWorkspaces,
419
+ conversationDirectory,
420
+ conversationDirectories,
421
+ sessionDirectories,
368
422
  agentPresets,
369
423
  models,
370
424
  contextEnhancement,
@@ -375,6 +429,9 @@ function storedDocument({
375
429
  busyMessageModes,
376
430
  }) {
377
431
  const document = { version, workspaces };
432
+ if (conversationDirectory) document.conversationDirectory = conversationDirectory;
433
+ if (Object.keys(conversationDirectories).length) document.conversationDirectories = conversationDirectories;
434
+ if (Object.keys(sessionDirectories).length) document.sessionDirectories = sessionDirectories;
378
435
  if (Object.keys(dsBotBindings).length > 0) document.dsBotBindings = dsBotBindings;
379
436
  if (Object.keys(busyMessageModes).length > 0) document.busyMessageModes = busyMessageModes;
380
437
  if (Object.keys(aliases).length > 0) document.aliases = aliases;
@@ -433,6 +490,7 @@ export class BotWorkspaceStore {
433
490
  #path;
434
491
  #defaultWorkspace;
435
492
  #ungroupedWorkspace;
493
+ #groupByAgentPreset;
436
494
  #version = 1;
437
495
  #workspaces = {};
438
496
  #agentPresets = {};
@@ -444,6 +502,9 @@ export class BotWorkspaceStore {
444
502
  #dsBotBindings = Object.create(null);
445
503
  #accessPolicies = Object.create(null);
446
504
  #conversationWorkspaces = Object.create(null);
505
+ #conversationDirectory = null;
506
+ #conversationDirectories = Object.create(null);
507
+ #sessionDirectories = Object.create(null);
447
508
  #generations = new Map();
448
509
  #nextGeneration = 1;
449
510
  #conversationGenerations = new Map();
@@ -456,11 +517,12 @@ export class BotWorkspaceStore {
456
517
  #writeQueue = Promise.resolve();
457
518
  #botQueues = new Map();
458
519
 
459
- constructor(path, { defaultWorkspace = defaultImWorkspace(), ungroupedWorkspace } = {}) {
520
+ constructor(path, { defaultWorkspace = defaultImWorkspace(), ungroupedWorkspace, groupByAgentPreset = false } = {}) {
460
521
  if (typeof path !== 'string' || !path) throw new TypeError('workspace store path is required');
461
522
  this.#path = path;
462
523
  this.#defaultWorkspace = resolve(defaultWorkspace);
463
524
  this.#ungroupedWorkspace = ungroupedWorkspace;
525
+ this.#groupByAgentPreset = groupByAgentPreset === true;
464
526
  }
465
527
 
466
528
  async load() {
@@ -477,6 +539,9 @@ export class BotWorkspaceStore {
477
539
  this.#dsBotBindings = normalized.dsBotBindings;
478
540
  this.#accessPolicies = normalized.accessPolicies;
479
541
  this.#conversationWorkspaces = normalized.conversationWorkspaces;
542
+ this.#conversationDirectory = normalized.conversationDirectory;
543
+ this.#conversationDirectories = normalized.conversationDirectories;
544
+ this.#sessionDirectories = normalized.sessionDirectories;
480
545
  } catch (error) {
481
546
  if (error?.code !== 'ENOENT') throw withConfigResource(error, 'workspace-config');
482
547
  this.#version = 1;
@@ -490,6 +555,9 @@ export class BotWorkspaceStore {
490
555
  this.#dsBotBindings = Object.create(null);
491
556
  this.#accessPolicies = Object.create(null);
492
557
  this.#conversationWorkspaces = Object.create(null);
558
+ this.#conversationDirectory = null;
559
+ this.#conversationDirectories = Object.create(null);
560
+ this.#sessionDirectories = Object.create(null);
493
561
  }
494
562
  this.#generations.clear();
495
563
  this.#nextGeneration = 1;
@@ -525,6 +593,112 @@ export class BotWorkspaceStore {
525
593
  return this.#workspaces[botIdOf(botId)] ?? this.#defaultWorkspace;
526
594
  }
527
595
 
596
+ conversationDirectoryFor(botId) {
597
+ const id = botIdOf(botId);
598
+ return { ...(Object.hasOwn(this.#conversationDirectories, id)
599
+ ? this.#conversationDirectories[id]
600
+ : this.#conversationDirectory ?? DEFAULT_CONVERSATION_DIRECTORY) };
601
+ }
602
+
603
+ conversationDirectoryOverrideFor(botId) {
604
+ const id = botIdOf(botId);
605
+ return Object.hasOwn(this.#conversationDirectories, id)
606
+ ? { ...this.#conversationDirectories[id] } : null;
607
+ }
608
+
609
+ async setConversationDirectory(botId, config, { incarnation } = {}) {
610
+ const id = botId === null ? null : botIdOf(botId);
611
+ const normalized = config === null ? null : validateConversationDirectory(config);
612
+ return this.#enqueue(id ?? '__channel__', async () => {
613
+ if (id !== null && (!this.has(id)
614
+ || (incarnation !== undefined && incarnation !== this.incarnationFor(id)))) {
615
+ const error = new Error('找不到要修改的机器人。');
616
+ error.code = 'workspace-bot-not-found';
617
+ throw error;
618
+ }
619
+ const previousDefault = this.#conversationDirectory;
620
+ const previousOverrides = { ...this.#conversationDirectories };
621
+ if (id === null) this.#conversationDirectory = normalized;
622
+ else if (normalized === null) delete this.#conversationDirectories[id];
623
+ else this.#conversationDirectories[id] = normalized;
624
+ try { await this.#persist(); }
625
+ catch (error) {
626
+ this.#conversationDirectory = previousDefault;
627
+ this.#conversationDirectories = previousOverrides;
628
+ throw error;
629
+ }
630
+ });
631
+ }
632
+
633
+ conversationDirectoryPathsFor(botId) {
634
+ return [...new Set(Object.values(this.#sessionDirectories[botIdOf(botId)] ?? {})
635
+ .flatMap((entry) => [entry.workspace, ...(entry.history ?? [])]))];
636
+ }
637
+
638
+ async prepareConversationDirectory(botId, conversationKey, {
639
+ explicitNew = false, incarnation, clearSession, onConversationGeneration,
640
+ } = {}) {
641
+ const id = botIdOf(botId);
642
+ if (!this.has(id) || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
643
+ const error = new Error('找不到要修改的机器人。');
644
+ error.code = 'workspace-bot-not-found';
645
+ throw error;
646
+ }
647
+ const config = this.conversationDirectoryFor(id);
648
+ if (!config.enabled) return null;
649
+ return this.#enqueue(id, async () => {
650
+ const existing = this.#sessionDirectories[id]?.[conversationKey];
651
+ const current = this.conversationWorkspaceFor(id, conversationKey);
652
+ const records = Object.values(this.#sessionDirectories[id] ?? {});
653
+ let base = existing?.base ?? current;
654
+ const visited = new Set();
655
+ while (!visited.has(base)) {
656
+ visited.add(base);
657
+ const parent = records.find((record) => record.workspace === base
658
+ || record.history?.includes(base))?.base;
659
+ if (!parent || parent === base) break;
660
+ base = parent;
661
+ }
662
+ const sameConfig = existing?.workspace === current && existing?.base === base
663
+ && existing?.strategy === config.strategy && existing?.prefix === config.prefix;
664
+ const reuse = sameConfig && (config.strategy === 'per-conversation'
665
+ || (!explicitNew && existing?.pending));
666
+ const timestamp = reuse ? existing.timestamp : Date.now();
667
+ const workspace = reuse ? existing.workspace : resolve(base, conversationDirectoryName(conversationKey, config, timestamp, `${this.#path}:${id}`));
668
+ try { await prepareDirectoryPath(base, workspace); }
669
+ catch (error) {
670
+ console.warn('[dsh-im] conversation directory preparation failed:', error?.message ?? error);
671
+ return { warning: '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。' };
672
+ }
673
+ const entries = { ...(this.#sessionDirectories[id] ?? {}), [conversationKey]: {
674
+ base, workspace, ...config, timestamp, pending: explicitNew,
675
+ history: existing && existing.workspace !== workspace
676
+ ? [...new Set([...(existing.history ?? []), existing.workspace])]
677
+ : existing?.history ?? [],
678
+ } };
679
+ const previousRecords = this.#sessionDirectories[id];
680
+ const previousOverrides = this.#conversationWorkspaces[id];
681
+ if (workspace !== current) {
682
+ const generation = this.publishConversationWorkspaceSwitch(id, conversationKey);
683
+ onConversationGeneration?.(generation);
684
+ await clearSession?.(conversationKey);
685
+ }
686
+ this.#sessionDirectories[id] = entries;
687
+ const overrides = { ...(this.#conversationWorkspaces[id] ?? {}), [conversationKey]: workspace };
688
+ this.#conversationWorkspaces[id] = overrides;
689
+ try { await this.#persist(); }
690
+ catch (error) {
691
+ if (previousRecords) this.#sessionDirectories[id] = previousRecords;
692
+ else delete this.#sessionDirectories[id];
693
+ if (previousOverrides) this.#conversationWorkspaces[id] = previousOverrides;
694
+ else delete this.#conversationWorkspaces[id];
695
+ console.warn('[dsh-im] conversation directory switch failed:', error?.message ?? error);
696
+ return { warning: '会话目录未生效:无法切换目录;本次仍在原工作区运行。' };
697
+ }
698
+ return { workspace };
699
+ });
700
+ }
701
+
528
702
  /**
529
703
  * An explicit override is stored even when it equals the current bot default,
530
704
  * so a later default change must never move a conversation that pinned its
@@ -549,6 +723,10 @@ export class BotWorkspaceStore {
549
723
  ) ?? null;
550
724
  }
551
725
 
726
+ groupsByAgentPreset(botId) {
727
+ return this.#groupByAgentPreset && !this.conversationDirectoryFor(botId).enabled;
728
+ }
729
+
552
730
  agentPresetFor(botId) {
553
731
  return this.#agentPresets[botIdOf(botId)] ?? null;
554
732
  }
@@ -842,6 +1020,7 @@ export class BotWorkspaceStore {
842
1020
 
843
1021
  async setWorkspace(botId, value, { clearSessions, incarnation } = {}) {
844
1022
  const id = botIdOf(botId);
1023
+ if (this.conversationDirectoryFor(id).enabled) throw workspaceManualEditDisabled();
845
1024
  if (!this.has(id)
846
1025
  || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
847
1026
  const error = new Error('找不到要修改的机器人。');
@@ -881,6 +1060,7 @@ export class BotWorkspaceStore {
881
1060
  incarnation,
882
1061
  } = {}) {
883
1062
  const id = botIdOf(botId);
1063
+ if (this.conversationDirectoryFor(id).enabled) throw workspaceManualEditDisabled();
884
1064
  if (typeof conversationKey !== 'string' || !conversationKey
885
1065
  || conversationKey.length > 1_024 || conversationKey.trim() !== conversationKey
886
1066
  || /[\u0000-\u001f\u007f]/u.test(conversationKey)) {
@@ -1169,6 +1349,7 @@ export class BotWorkspaceStore {
1169
1349
  incarnation,
1170
1350
  expectedGeneration,
1171
1351
  expectedConversationGeneration,
1352
+ preserveBotWorkspace = false,
1172
1353
  } = {}) {
1173
1354
  const id = botIdOf(botId);
1174
1355
  if (typeof conversationKey !== 'string' || !conversationKey
@@ -1199,6 +1380,10 @@ export class BotWorkspaceStore {
1199
1380
  const workspace = await canonicalWorkspacePath(await validateWorkspacePath(value, {
1200
1381
  ungroupedWorkspace: this.#ungroupedWorkspace,
1201
1382
  }));
1383
+ if (this.conversationDirectoryFor(id).enabled
1384
+ && !(await sameWorkspacePath(workspace, this.conversationWorkspaceFor(id, conversationKey)))) {
1385
+ throw workspaceManualEditDisabled();
1386
+ }
1202
1387
  return this.#enqueue(id, async () => {
1203
1388
  if (!this.has(id)
1204
1389
  || (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
@@ -1216,6 +1401,20 @@ export class BotWorkspaceStore {
1216
1401
  // workspace switch queued while the session was being adopted must not be
1217
1402
  // silently overwritten by the binding that started before it.
1218
1403
  assertConversationCurrent();
1404
+ if (this.conversationDirectoryFor(id).enabled || preserveBotWorkspace) {
1405
+ if (!preserveBotWorkspace
1406
+ && !(await sameWorkspacePath(workspace, this.conversationWorkspaceFor(id, conversationKey)))) {
1407
+ throw workspaceManualEditDisabled();
1408
+ }
1409
+ assertConversationCurrent();
1410
+ await setSession(conversationKey, sessionId);
1411
+ assertConversationCurrent();
1412
+ return {
1413
+ workspace, sessionId,
1414
+ generation: this.#generations.get(id),
1415
+ conversationGeneration,
1416
+ };
1417
+ }
1219
1418
  const sameWorkspace = await sameWorkspacePath(workspace, this.workspaceFor(id));
1220
1419
  const previousOverrides = this.#conversationWorkspaces[id];
1221
1420
  const override = previousOverrides?.[conversationKey];
@@ -1371,6 +1570,8 @@ export class BotWorkspaceStore {
1371
1570
  ...Object.keys(this.#deliveryTargets),
1372
1571
  ...Object.keys(this.#accessPolicies),
1373
1572
  ...Object.keys(this.#conversationWorkspaces),
1573
+ ...Object.keys(this.#conversationDirectories),
1574
+ ...Object.keys(this.#sessionDirectories),
1374
1575
  ...this.#dirtyRemovals,
1375
1576
  ]);
1376
1577
  for (const botId of candidates) {
@@ -1382,11 +1583,14 @@ export class BotWorkspaceStore {
1382
1583
  if (!status || typeof status !== 'object' || !Array.isArray(status.bots)) return status;
1383
1584
  return {
1384
1585
  ...status,
1586
+ conversationDirectory: this.#conversationDirectory ? { ...this.#conversationDirectory } : null,
1385
1587
  bots: status.bots.map((bot) => bot?.botId
1386
1588
  ? {
1387
1589
  ...bot,
1388
1590
  ...(this.aliasFor(bot.botId) ? { bot: withBotAlias(bot.bot, this.aliasFor(bot.botId)) } : {}),
1389
1591
  workspace: this.workspaceFor(bot.botId),
1592
+ conversationDirectory: this.conversationDirectoryFor(bot.botId),
1593
+ conversationDirectoryOverride: this.conversationDirectoryOverrideFor(bot.botId),
1390
1594
  agentPreset: this.agentPresetFor(bot.botId),
1391
1595
  model: this.modelFor(bot.botId),
1392
1596
  contextEnhancement: this.contextEnhancementFor(bot.botId),
@@ -1435,8 +1639,10 @@ export class BotWorkspaceStore {
1435
1639
  const hadDsBotBindings = Object.hasOwn(this.#dsBotBindings, id);
1436
1640
  const hadAccessPolicy = Object.hasOwn(this.#accessPolicies, id);
1437
1641
  const hadConversationWorkspaces = Object.hasOwn(this.#conversationWorkspaces, id);
1642
+ const hadDirectoryRecords = Object.hasOwn(this.#conversationDirectories, id) || Object.hasOwn(this.#sessionDirectories, id);
1438
1643
  const needsCleanup = hadWorkspace || hadPreset || hadModel || hadAlias || hadContextEnhancement
1439
1644
  || hadDeliveryTargets || hadDsBotBindings || hadAccessPolicy || hadConversationWorkspaces || hadMessageMode
1645
+ || hadDirectoryRecords
1440
1646
  || this.#dirtyRemovals.has(id);
1441
1647
  delete this.#workspaces[id];
1442
1648
  delete this.#agentPresets[id];
@@ -1448,6 +1654,8 @@ export class BotWorkspaceStore {
1448
1654
  delete this.#dsBotBindings[id];
1449
1655
  delete this.#accessPolicies[id];
1450
1656
  delete this.#conversationWorkspaces[id];
1657
+ delete this.#conversationDirectories[id];
1658
+ delete this.#sessionDirectories[id];
1451
1659
  this.#generations.delete(id);
1452
1660
  this.#incarnations.delete(id);
1453
1661
  if (!needsCleanup) return {
@@ -1486,6 +1694,9 @@ export class BotWorkspaceStore {
1486
1694
  conversationWorkspaces = this.#conversationWorkspaces,
1487
1695
  busyMessageModes = this.#busyMessageModes,
1488
1696
  dsBotBindings = this.#dsBotBindings,
1697
+ conversationDirectory = this.#conversationDirectory,
1698
+ conversationDirectories = this.#conversationDirectories,
1699
+ sessionDirectories = this.#sessionDirectories,
1489
1700
  ) {
1490
1701
  await writeStoredDocument(this.#path, storedDocument({
1491
1702
  version,
@@ -1499,6 +1710,9 @@ export class BotWorkspaceStore {
1499
1710
  accessPolicies,
1500
1711
  aliases,
1501
1712
  busyMessageModes,
1713
+ conversationDirectory,
1714
+ conversationDirectories,
1715
+ sessionDirectories,
1502
1716
  }));
1503
1717
  this.#dirtyRemovals.clear();
1504
1718
  }
@@ -1821,6 +2035,10 @@ export function createBotWorkspaceScope(
1821
2035
  throw unavailableAgentPreset();
1822
2036
  }
1823
2037
  }
2038
+ if (workspaces.groupsByAgentPreset?.(botId)) {
2039
+ await ensurePresetWorkspace(target, workspaces.workspaceFor(botId), agentPreset, catalog, options);
2040
+ assertCurrentBotScope(isCurrentScope);
2041
+ }
1824
2042
  await workspaces.setAgentPreset(botId, agentPreset, { incarnation });
1825
2043
  assertCurrentBotScope(isCurrentScope);
1826
2044
  if (catalog) {
@@ -1885,6 +2103,9 @@ export function createBotWorkspaceScope(
1885
2103
  }
1886
2104
  if (property === 'switchWorkspace') {
1887
2105
  return (workspace) => {
2106
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2107
+ return Promise.reject(workspaceManualEditDisabled());
2108
+ }
1888
2109
  if (workspaces.listDsBotBindings(botId).length > 0) {
1889
2110
  throw deliveryTargetError('ds-bot-bound', '请先解除 DS Bot 绑定,再切换机器人工作目录。');
1890
2111
  }
@@ -1909,6 +2130,71 @@ export function createBotWorkspaceScope(
1909
2130
  return workspaces.conversationWorkspaceFor(botId, conversationKey);
1910
2131
  };
1911
2132
  }
2133
+ if (property === 'resolveConversationWorkspace') {
2134
+ return async (conversationKey, options = {}) => {
2135
+ options.signal?.throwIfAborted();
2136
+ assertCurrentBotScope(isCurrentScope);
2137
+ const pending = pendingConversationSwitches.get(conversationKey);
2138
+ if (pending) await pending;
2139
+ await workspaces.whenBotIdle(botId);
2140
+ assertCurrentBotScope(isCurrentScope);
2141
+ const generation = workspaces.generationFor(botId);
2142
+ const conversationGeneration = currentConversationGeneration(conversationKey);
2143
+ const sessionId = scopedState.sessionFor(conversationKey);
2144
+ const configured = workspaces.conversationWorkspaceFor(botId, conversationKey);
2145
+ const preset = workspaces.agentPresetFor(botId);
2146
+ const assertUnchanged = () => {
2147
+ options.signal?.throwIfAborted();
2148
+ assertCurrentBotScope(isCurrentScope);
2149
+ if (generation !== workspaces.generationFor(botId)
2150
+ || conversationGenerationIsStale(conversationKey, conversationGeneration)
2151
+ || sessionId !== scopedState.sessionFor(conversationKey)
2152
+ || (!sessionId && preset !== workspaces.agentPresetFor(botId))) {
2153
+ throw workspaceSessionStale('The conversation changed while its workspace was being resolved.');
2154
+ }
2155
+ };
2156
+ if (sessionId) {
2157
+ const known = sessionGenerations.get(sessionId)?.workspace;
2158
+ if (known) {
2159
+ assertUnchanged();
2160
+ return known;
2161
+ }
2162
+ // The configured bot directory stays unchanged when a preset groups
2163
+ // a new session. Recover its actual owner after a restart, without
2164
+ // adopting the session or moving an older chat to the new preset.
2165
+ if (typeof target.rpc === 'function') {
2166
+ const listed = await target.rpc('workspace.list', {}, 30_000, options);
2167
+ assertUnchanged();
2168
+ if (!Array.isArray(listed?.items)) throw new TypeError('Harness returned an invalid workspace list');
2169
+ const owners = listed.items.filter((item) => Array.isArray(item?.sessionIds)
2170
+ && item.sessionIds.includes(sessionId));
2171
+ if (owners.length > 1) throw new TypeError('Harness returned multiple session workspaces');
2172
+ const workspace = owners[0]?.path ?? configured;
2173
+ if (typeof workspace !== 'string' || !isAbsolute(workspace)) {
2174
+ throw new TypeError('Harness returned an invalid session workspace');
2175
+ }
2176
+ sessionGenerations.set(sessionId, { ...sessionGenerations.get(sessionId), workspace });
2177
+ return workspace;
2178
+ }
2179
+ return configured;
2180
+ }
2181
+ // With no binding (including after /new), list the next preset's
2182
+ // existing group. A read never creates a directory or registers it.
2183
+ if (preset && workspaces.groupsByAgentPreset?.(botId)
2184
+ && !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
2185
+ && await target.isUngroupedWorkspace?.(configured)) {
2186
+ const directory = join(configured, 'presets', preset);
2187
+ const exists = await stat(directory).then((entry) => entry.isDirectory(), (error) => {
2188
+ if (error?.code === 'ENOENT') return false;
2189
+ throw error;
2190
+ });
2191
+ assertUnchanged();
2192
+ if (exists) return directory;
2193
+ }
2194
+ assertUnchanged();
2195
+ return configured;
2196
+ };
2197
+ }
1912
2198
  if (property === 'hasConversationWorkspaceOverride') {
1913
2199
  return (conversationKey) => {
1914
2200
  assertCurrentBotScope(isCurrentScope);
@@ -1926,8 +2212,32 @@ export function createBotWorkspaceScope(
1926
2212
  // bind and the send so a late switch cannot be outrun.
1927
2213
  return (conversationKey) => currentConversationGeneration(conversationKey);
1928
2214
  }
2215
+ if (property === 'conversationDirectoryConfig') {
2216
+ return () => workspaces.conversationDirectoryFor(botId);
2217
+ }
2218
+ if (property === 'conversationDirectoryPaths') {
2219
+ return () => workspaces.conversationDirectoryPathsFor(botId);
2220
+ }
2221
+ if (property === 'prepareConversationDirectory') {
2222
+ return async (conversationKey, options = {}) => {
2223
+ assertCurrentBotScope(isCurrentScope);
2224
+ assertNoDsBinding(conversationKey);
2225
+ const pending = pendingConversationSwitches.get(conversationKey);
2226
+ if (pending) await pending;
2227
+ assertCurrentBotScope(isCurrentScope);
2228
+ return trackConversationSwitch(conversationKey, workspaces.prepareConversationDirectory(botId, conversationKey, {
2229
+ ...options,
2230
+ incarnation,
2231
+ clearSession: (key) => state.clearSession(key),
2232
+ onConversationGeneration: (generation) => maskConversationSwitch(conversationKey, generation),
2233
+ }));
2234
+ };
2235
+ }
1929
2236
  if (property === 'switchConversationWorkspace') {
1930
2237
  return (conversationKey, workspace) => {
2238
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2239
+ return Promise.reject(workspaceManualEditDisabled());
2240
+ }
1931
2241
  assertNoDsBinding(conversationKey);
1932
2242
  if (!isCurrentScope()) {
1933
2243
  const error = new Error('找不到要修改的机器人。');
@@ -1950,6 +2260,9 @@ export function createBotWorkspaceScope(
1950
2260
  }
1951
2261
  if (property === 'clearConversationWorkspace') {
1952
2262
  return (conversationKey) => {
2263
+ if (workspaces.conversationDirectoryFor(botId).enabled) {
2264
+ return Promise.reject(workspaceManualEditDisabled());
2265
+ }
1953
2266
  assertNoDsBinding(conversationKey);
1954
2267
  if (!isCurrentScope()) {
1955
2268
  const error = new Error('找不到要修改的机器人。');
@@ -2006,6 +2319,17 @@ export function createBotWorkspaceScope(
2006
2319
  || adopted.sessionId !== sessionId || typeof adopted.workspace !== 'string') {
2007
2320
  throw new TypeError('Harness returned an invalid adopted workspace session');
2008
2321
  }
2322
+ // Selecting another session in the current automatic group must not
2323
+ // turn that group into the bot's manual directory and clear every
2324
+ // other conversation. Explicit cross-workspace selection keeps its
2325
+ // existing bot-wide semantics.
2326
+ const baseWorkspace = workspaces.workspaceFor(botId);
2327
+ const preserveBotWorkspace = !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
2328
+ && normalizeAgentPresetId(basename(adopted.workspace)) !== null
2329
+ && await target.isUngroupedWorkspace?.(baseWorkspace)
2330
+ && await sameWorkspacePath(dirname(adopted.workspace), join(baseWorkspace, 'presets'))
2331
+ && await sameWorkspacePath(adopted.workspace,
2332
+ await scopedHarness.resolveConversationWorkspace(conversationKey));
2009
2333
  const bound = await workspaces.bindWorkspaceSession(botId, adopted.workspace, {
2010
2334
  conversationKey,
2011
2335
  sessionId,
@@ -2016,6 +2340,7 @@ export function createBotWorkspaceScope(
2016
2340
  incarnation,
2017
2341
  expectedGeneration,
2018
2342
  expectedConversationGeneration,
2343
+ preserveBotWorkspace,
2019
2344
  });
2020
2345
  if (!isCurrentScope()) {
2021
2346
  const error = new Error('找不到要修改的机器人。');
@@ -2046,6 +2371,10 @@ export function createBotWorkspaceScope(
2046
2371
  return async (options = {}) => {
2047
2372
  const { inheritBotModel = true, conversationKey, ...createOptions } = options;
2048
2373
  assertNoDsBinding(conversationKey);
2374
+ if (conversationKey) {
2375
+ const prepared = await scopedHarness.prepareConversationDirectory(conversationKey);
2376
+ if (prepared?.workspace) createOptions.workspace = prepared.workspace;
2377
+ }
2049
2378
  // /conv publishes its generation before path validation enters the
2050
2379
  // bot queue. Wait for both phases before pairing a workspace with its
2051
2380
  // generation; otherwise a new session can carry a new fence but old cwd.
@@ -2066,7 +2395,13 @@ export function createBotWorkspaceScope(
2066
2395
  : null;
2067
2396
  const agentPreset = workspaces.agentPresetFor(botId);
2068
2397
  const model = inheritBotModel === false ? null : workspaces.modelFor(botId);
2069
- const workspace = workspaces.conversationWorkspaceFor(botId, conversationKey);
2398
+ let workspace = workspaces.conversationWorkspaceFor(botId, conversationKey);
2399
+ if (agentPreset && workspaces.groupsByAgentPreset?.(botId)
2400
+ && !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)) {
2401
+ const settings = await presetSettings();
2402
+ workspace = await ensurePresetWorkspace(target, workspace, agentPreset, settings.agentPresetCatalog, options);
2403
+ assertCurrentBotScope(isCurrentScope);
2404
+ }
2070
2405
  const sessionId = await target.createSession({
2071
2406
  ...createOptions,
2072
2407
  workspace,
@@ -2180,9 +2515,23 @@ export function createBotWorkspaceScope(
2180
2515
  return invokeStartedSessionMutation('renameSession', args, 'title rename');
2181
2516
  },
2182
2517
  } : {}),
2183
- selectModel(...args) {
2184
- if (dsBotId) throw deliveryTargetError('ds-bot-bound', '请在 DS Bot 中修改模型。');
2185
- return invokeCurrentSession('selectSessionModel', args, 'model selection');
2518
+ async selectModel(selection, options = {}) {
2519
+ if (!dsBotId) {
2520
+ return invokeCurrentSession('selectSessionModel', [selection, options], 'model selection');
2521
+ }
2522
+ options.signal?.throwIfAborted();
2523
+ if (!isCurrentSession()) throw workspaceSessionStale('DS Bot binding changed before model selection.');
2524
+ const bot = await dsBot?.resolve(dsBotId);
2525
+ options.signal?.throwIfAborted();
2526
+ if (!bot || bot.sessionId !== sessionId || !isCurrentSession()) {
2527
+ throw workspaceSessionStale('DS Bot changed before model selection.');
2528
+ }
2529
+ if (typeof dsBot.updateBotModel !== 'function') {
2530
+ throw deliveryTargetError('ds-bot-unavailable', 'DS Bot model selection is unavailable.');
2531
+ }
2532
+ // This is a Bot-wide setting. Never mutate only the IM session: DS
2533
+ // Bot applies the choice to its own and group sessions as well.
2534
+ return dsBot.updateBotModel(dsBotId, selection, options);
2186
2535
  },
2187
2536
  isRunning(...args) {
2188
2537
  return invokeCurrentSession('isSessionRunning', args, 'run-state check');
@@ -2313,6 +2662,7 @@ export function createBotScopedHarness(harness, options) {
2313
2662
 
2314
2663
  export function createWorkspaceAwareController(controller, {
2315
2664
  workspaces,
2665
+ harness,
2316
2666
  stateFor,
2317
2667
  agentPresetCatalog,
2318
2668
  modelCatalog,
@@ -2373,6 +2723,9 @@ export function createWorkspaceAwareController(controller, {
2373
2723
  && !catalog?.items.some((item) => item.id === normalizedAgentPreset)) {
2374
2724
  throw unavailableAgentPreset();
2375
2725
  }
2726
+ if (workspaces.groupsByAgentPreset?.(botId)) {
2727
+ await ensurePresetWorkspace(harness, workspaces.workspaceFor(botId), normalizedAgentPreset, catalog);
2728
+ }
2376
2729
  await workspaces.setAgentPreset(botId, normalizedAgentPreset, { incarnation });
2377
2730
  return decorateResult(
2378
2731
  workspaces,
@@ -2561,6 +2914,16 @@ export function createWorkspaceAwareController(controller, {
2561
2914
 
2562
2915
  return new Proxy(controller, {
2563
2916
  get(target, property) {
2917
+ if (property === 'updateConversationDirectory') {
2918
+ return async (botId, config) => {
2919
+ await workspaces.setConversationDirectory(
2920
+ botId,
2921
+ config,
2922
+ botId === null ? {} : { incarnation: workspaces.incarnationFor(botId) },
2923
+ );
2924
+ return decorate(await controller.status());
2925
+ };
2926
+ }
2564
2927
  if (property === 'updateWorkspace') return updateWorkspace;
2565
2928
  if (property === 'updateAgentPreset') return updateAgentPreset;
2566
2929
  if (property === 'updateModel') return updateModel;