@xmanrui/dsh-im 5.7.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 (29) hide show
  1. package/lib/client.js +342 -159
  2. package/lib/index.js +323 -321
  3. package/package.json +1 -1
  4. package/plugin-src/client/channels/feishu/api.js +5 -0
  5. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  6. package/plugin-src/client/channels/feishu/index.js +1 -0
  7. package/plugin-src/client/delivery-settings.js +4 -0
  8. package/plugin-src/client/i18n-ru.js +17 -0
  9. package/plugin-src/client/i18n.js +17 -0
  10. package/plugin-src/client/styles.js +6 -0
  11. package/plugin-src/client/workspace-editor.js +6 -5
  12. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  13. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  14. package/scripts/verify-package.mjs +17 -6
  15. package/src/channels/feishu/bridge.mjs +29 -12
  16. package/src/channels/feishu/message-utils.mjs +1 -0
  17. package/src/channels/shared/bot-workspace-store.mjs +248 -0
  18. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  19. package/src/channels/shared/conversation-directory.mjs +29 -0
  20. package/src/channels/shared/harness-client.mjs +72 -2
  21. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  22. package/src/channels/shared/i18n-en/shared-a.mjs +5 -0
  23. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  24. package/src/channels/shared/i18n-ru/shared-a.mjs +5 -0
  25. package/src/channels/shared/message-failure.mjs +8 -0
  26. package/src/channels/shared/new-command.mjs +7 -0
  27. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  28. package/src/channels/shared/text-harness-bridge.mjs +3 -2
  29. package/src/channels/shared/workspace-command.mjs +22 -9
@@ -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;
@@ -0,0 +1,46 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, realpath, stat } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { validateConversationDirectory } from './conversation-directory.mjs';
5
+
6
+ let lastSessionTimestamp = 0;
7
+
8
+ export function conversationDirectoryName(conversationKey, value, timestamp = Date.now(), identity = '') {
9
+ const config = validateConversationDirectory(value);
10
+ if (config.strategy === 'per-session') {
11
+ timestamp = Math.max(Number(timestamp) || 0, lastSessionTimestamp + 1);
12
+ lastSessionTimestamp = timestamp;
13
+ }
14
+ const digest = createHash('sha256').update(JSON.stringify([identity, conversationKey])).digest('hex').slice(0, 16);
15
+ const suffix = `-${digest}${config.strategy === 'per-session' ? `-${timestamp}` : ''}`;
16
+ const readable = conversationKey.replace(/[<>:"/\\|?*\u0000-\u001f\u007f]/gu, '-');
17
+ const room = Math.max(0, 100 - config.prefix.length - suffix.length);
18
+ return `${config.prefix}${readable.slice(0, room)}${suffix}`;
19
+ }
20
+
21
+ export async function prepareDirectoryPath(base, directory) {
22
+ const root = await realpath(resolve(base));
23
+ const target = resolve(directory);
24
+ if (dirname(target) !== root) throw new Error('会话目录必须直接位于基工作区下。');
25
+ try {
26
+ const info = await stat(target);
27
+ if (!info.isDirectory()) throw new Error('会话目录路径不是目录。');
28
+ if ((await realpath(target)) !== target) throw new Error('会话目录不能是符号链接。');
29
+ } catch (error) {
30
+ if (error.code !== 'ENOENT') throw error;
31
+ await mkdir(target, { recursive: false, mode: 0o700 });
32
+ }
33
+ return target;
34
+ }
35
+
36
+ export async function ensureConversationDirectory({ baseWorkspace, conversationKey, config, sessionTimestamp }) {
37
+ const normalized = validateConversationDirectory(config);
38
+ const directory = resolve(baseWorkspace, conversationDirectoryName(conversationKey, normalized, sessionTimestamp));
39
+ try {
40
+ await prepareDirectoryPath(baseWorkspace, directory);
41
+ return { workspace: directory };
42
+ } catch (error) {
43
+ console.warn('[dsh-im] conversation directory preparation failed:', error?.message ?? error);
44
+ return { warning: '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。' };
45
+ }
46
+ }
@@ -0,0 +1,29 @@
1
+ export const DEFAULT_CONVERSATION_DIRECTORY = Object.freeze({
2
+ enabled: false,
3
+ strategy: 'per-conversation',
4
+ prefix: 'conv-',
5
+ });
6
+
7
+ export function validateConversationDirectory(value) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value)
9
+ || Object.keys(value).some((key) => !['enabled', 'strategy', 'prefix'].includes(key))
10
+ || typeof value.enabled !== 'boolean'
11
+ || (value.strategy !== undefined && !['per-conversation', 'per-session'].includes(value.strategy))
12
+ || (value.prefix !== undefined && (typeof value.prefix !== 'string' || !/^[A-Za-z0-9_-]{1,32}$/.test(value.prefix)))) {
13
+ const error = new Error('会话目录设置无效:前缀须为 1–32 位字母、数字、下划线或连字符。');
14
+ error.code = 'conversation-directory-invalid';
15
+ throw error;
16
+ }
17
+ return { ...DEFAULT_CONVERSATION_DIRECTORY, ...value };
18
+ }
19
+
20
+ export function normalizeConversationDirectory(value) {
21
+ if (value === null || value === undefined) return null;
22
+ try { return validateConversationDirectory(value); } catch { return null; }
23
+ }
24
+
25
+ export function workspaceManualEditDisabled() {
26
+ const error = new Error('会话目录隔离已开启,无法手动修改工作区。');
27
+ error.code = 'workspace-manual-edit-disabled';
28
+ return error;
29
+ }
@@ -891,6 +891,16 @@ export class HarnessTransportError extends Error {
891
891
  }
892
892
  }
893
893
 
894
+ /**
895
+ * session.prompt 提交超时(30 秒窗口到期)只说明应答迟到,不代表提交失败:
896
+ * 单进程 Host 忙碌时 prompt 往往已入队。这类错误需要先回查持久账本再定性。
897
+ */
898
+ function isPromptSubmitTimeout(error) {
899
+ return error instanceof HarnessTransportError
900
+ && error.code === 'harness-timeout'
901
+ && error.method === 'session.prompt';
902
+ }
903
+
894
904
  export class HarnessHealthError extends Error {
895
905
  constructor(cause) {
896
906
  super('Harness health RPC was rejected', { cause });
@@ -1434,6 +1444,46 @@ export class HarnessClient {
1434
1444
  }
1435
1445
  }
1436
1446
 
1447
+ /**
1448
+ * 提交超时后的入库确认:session.history 是持久账本,按 promptRpcId 找回我们的
1449
+ * 持久化痕迹(已执行的 user/message,或已入队待执行的 agent/inbox/spliced
1450
+ * 回执)即视为提交已成功,让 ask() 继续等回复而不是误报失败。
1451
+ * 确认探测自身的失败一律吞掉——它们不能掩盖或改变原始提交超时的定性;
1452
+ * 唯独取消例外:取消原因必须优先于超时透出。
1453
+ */
1454
+ async #confirmPromptSubmit(sessionId, promptRpcId, { signal } = {}) {
1455
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1456
+ if (signal?.aborted) return false;
1457
+ try {
1458
+ const history = await this.#sessionRpc('session.history', {
1459
+ sessionId,
1460
+ maxMessages: 50,
1461
+ }, 30_000, { signal });
1462
+ const confirmed = (history?.events ?? []).some((entry) => {
1463
+ const event = entry?.event ?? entry;
1464
+ if (event?.type === 'user/message') {
1465
+ return event?.data?.source?.rpcId === promptRpcId;
1466
+ }
1467
+ // queue 模式下消息可能已持久入队但尚未产生 user/message:
1468
+ // agent/inbox/spliced 的 inserted[].source.rpcId 就是入队回执。
1469
+ if (event?.type === 'agent/inbox/spliced') {
1470
+ return (event?.data?.inserted ?? [])
1471
+ .some((message) => message?.source?.rpcId === promptRpcId);
1472
+ }
1473
+ return false;
1474
+ });
1475
+ if (confirmed) return true;
1476
+ } catch (probeError) {
1477
+ // 取消优先于超时定性:最后一次探测期间被取消时,循环后面没有
1478
+ // sleep 再检查 abort,必须在这里把取消原因抛出,不能被超时覆盖。
1479
+ if (signal?.aborted) throw signal.reason ?? probeError;
1480
+ // 其余账本探测失败不改变定性:本轮未确认,继续轮询或最终按原超时上报。
1481
+ }
1482
+ if (attempt < 4) await sleep(2_000, signal);
1483
+ }
1484
+ return false;
1485
+ }
1486
+
1437
1487
  async sessionExists(sessionId, options = {}) {
1438
1488
  // Archived Sessions still exist. Returning false here would silently bind
1439
1489
  // the conversation to a new Session; reading their active log can also fail.
@@ -2037,8 +2087,28 @@ export class HarnessClient {
2037
2087
  ...timeZoneFields,
2038
2088
  }, 30_000, { rpcId: promptRpcId, signal });
2039
2089
  };
2090
+ // 30 秒提交窗口到期只说明 Host 忙到没来得及应答,prompt 可能早已入队。
2091
+ // 先按 promptRpcId 回查持久账本,确认入库就继续等回复;确认不到才把
2092
+ // 原始超时错误向上抛,由文案层标注「提交请求超时、是否送达未知」。
2093
+ const submitPrompt = async (promptContent) => {
2094
+ try {
2095
+ await sendPrompt(promptContent);
2096
+ } catch (error) {
2097
+ if (!isPromptSubmitTimeout(error) || signal?.aborted) throw error;
2098
+ let confirmed = false;
2099
+ try {
2100
+ confirmed = await this.#confirmPromptSubmit(sessionId, promptRpcId, { signal });
2101
+ } catch (confirmError) {
2102
+ // 确认途中被取消时恢复调用方的取消语义(与图片暂存路径一致)。
2103
+ if (signal?.aborted) throw signal.reason ?? confirmError;
2104
+ throw error;
2105
+ }
2106
+ if (!confirmed) throw error;
2107
+ diagnostic.submissionState = 'accepted';
2108
+ }
2109
+ };
2040
2110
  try {
2041
- await sendPrompt(content);
2111
+ await submitPrompt(content);
2042
2112
  } catch (error) {
2043
2113
  // The Host refuses image blocks for a non-vision model before any
2044
2114
  // durable user message exists. Re-deliver the same bytes the way
@@ -2073,7 +2143,7 @@ export class HarnessClient {
2073
2143
  ...contentWithoutImages(baseContent),
2074
2144
  { type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
2075
2145
  ], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
2076
- await sendPrompt(fallbackPrompt);
2146
+ await submitPrompt(fallbackPrompt);
2077
2147
  }
2078
2148
  promptAccepted = true;
2079
2149
  diagnostic.submissionState = 'accepted';
@@ -28,6 +28,8 @@ export default Object.freeze({
28
28
  'Message preparation failed before submission. It has not been submitted for execution. Try again; if this persists, share the reference with your administrator.',
29
29
  '消息已尝试提交,但任务结果尚未确认。请先到 DSH 查看状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
30
30
  'Message submission was attempted, but the task outcome is unconfirmed. Check its status in DSH before resubmitting; if this persists, share the reference with your administrator.',
31
+ '消息提交请求超时,未能确认消息是否已送达 DSH。请稍后到 DSH 查看该会话状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
32
+ 'The message submission request timed out and delivery to DSH could not be confirmed. Check the session status in DSH before resubmitting; if this persists, share the reference with your administrator.',
31
33
  "DSH 版本": "DSH version",
32
34
  "依赖版本": "Dependency versions",
33
35
  "代理已配置": "Proxy configured",
@@ -1,5 +1,10 @@
1
1
  // English translations (shared-a area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请发送你的问题。': 'Please send your question.',
4
+ '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。':
5
+ 'Conversation directory isolation did not take effect: the directory could not be created. This session will use the original workspace.',
6
+ '会话目录未生效:无法切换目录;本次仍在原工作区运行。':
7
+ 'Conversation directory isolation did not take effect: the directory could not be selected. This session will use the original workspace.',
3
8
  '这个问题已在其他客户端处理,无需再次回答。':
4
9
  'This question has already been answered from another client; no further reply is needed.',
5
10
  '任务已完成。': 'Task completed.',
@@ -28,6 +28,8 @@ export default Object.freeze({
28
28
  'Обработка сообщения до отправки не удалась, на выполнение оно не ушло. Повторите попытку; если ошибка повторяется, передайте администратору номер обращения.',
29
29
  '消息已尝试提交,但任务结果尚未确认。请先到 DSH 查看状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
30
30
  'Сообщение отправлено, но результат задачи пока не подтверждён. Сначала проверьте состояние в DSH и не отправляйте повторно; если ошибка повторяется, передайте администратору номер обращения.',
31
+ '消息提交请求超时,未能确认消息是否已送达 DSH。请稍后到 DSH 查看该会话状态,不要立即重复提交;若持续发生,请将参考号提供给管理员。':
32
+ 'Время ожидания запроса на отправку сообщения истекло, и доставку в DSH подтвердить не удалось. Позже проверьте состояние этой сессии в DSH и не отправляйте сообщение повторно сразу; если ошибка повторяется, передайте администратору номер обращения.',
31
33
  'DSH 版本': 'Версия DSH',
32
34
  '依赖版本': 'Версии зависимостей',
33
35
  '代理已配置': 'Прокси настроен',
@@ -1,5 +1,10 @@
1
1
  // Russian translations (shared-a area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '请发送你的问题。': 'Отправьте свой вопрос.',
4
+ '会话目录未生效:无法创建目录(权限或磁盘空间不足);本次仍在原工作区运行。':
5
+ 'Изоляция каталога беседы не применена: не удалось создать каталог (недостаточно прав или места на диске). Этот сеанс продолжит работу в исходной рабочей области.',
6
+ '会话目录未生效:无法切换目录;本次仍在原工作区运行。':
7
+ 'Изоляция каталога беседы не применена: не удалось переключить каталог. Этот сеанс продолжит работу в исходной рабочей области.',
3
8
  '这个问题已在其他客户端处理,无需再次回答。':
4
9
  'На этот вопрос уже ответили в другом клиенте, повторять ответ не нужно.',
5
10
  '任务已完成。': 'Задача выполнена.',