@xmanrui/dsh-im 5.8.0 → 5.9.1

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 (66) hide show
  1. package/README.en.md +45 -8
  2. package/README.md +56 -8
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +66 -7
  5. package/lib/index.js +329 -326
  6. package/package.json +3 -1
  7. package/plugin-src/client/connection-error.js +1 -1
  8. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  9. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  10. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  11. package/plugin-src/host/channels/qq/production.mjs +2 -1
  12. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  13. package/plugin-src/host/channels/shared/production.mjs +32 -3
  14. package/plugin-src/host/channels/slack/production.mjs +2 -1
  15. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  16. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  17. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  18. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  19. package/plugin-src/host/delivery-adapter.mjs +122 -1
  20. package/plugin-src/host/delivery-service.mjs +40 -0
  21. package/plugin-src/host/ds-bot-client.mjs +28 -2
  22. package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
  23. package/plugin-src/host/index.mjs +25 -2
  24. package/plugin-src/host/modern-harness-api.mjs +3 -0
  25. package/plugin-src/host/sidebar-settings.mjs +1 -2
  26. package/plugin-src/host/update-rpc.mjs +1 -1
  27. package/plugin-src/management-rpc.mjs +25 -3
  28. package/scripts/telegram-menu-scopes.mjs +57 -0
  29. package/scripts/verify-interface-language.mjs +60 -15
  30. package/scripts/verify-lan-management.mjs +58 -5
  31. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  32. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  33. package/src/channels/email/email-runtime.mjs +27 -8
  34. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  35. package/src/channels/feishu/bridge.mjs +296 -13
  36. package/src/channels/feishu/feishu-cards.mjs +96 -25
  37. package/src/channels/qq/qq-menu.mjs +3 -4
  38. package/src/channels/shared/action-card.mjs +331 -0
  39. package/src/channels/shared/bot-workspace-store.mjs +123 -8
  40. package/src/channels/shared/command-catalog.mjs +20 -5
  41. package/src/channels/shared/conversation/describe.mjs +116 -0
  42. package/src/channels/shared/conversation-state-store.mjs +62 -0
  43. package/src/channels/shared/diagnostic-details.mjs +38 -0
  44. package/src/channels/shared/harness-approval.mjs +58 -13
  45. package/src/channels/shared/harness-client.mjs +13 -0
  46. package/src/channels/shared/harness-session-binding.mjs +13 -1
  47. package/src/channels/shared/i18n-en/diagnostics.mjs +6 -1
  48. package/src/channels/shared/i18n-en/feishu.mjs +9 -0
  49. package/src/channels/shared/i18n-en/shared-a.mjs +9 -0
  50. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  51. package/src/channels/shared/i18n-ru/diagnostics.mjs +10 -0
  52. package/src/channels/shared/i18n-ru/feishu.mjs +8 -0
  53. package/src/channels/shared/i18n-ru/shared-a.mjs +9 -0
  54. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  55. package/src/channels/shared/model-command.mjs +5 -0
  56. package/src/channels/shared/preset-workspaces.mjs +48 -0
  57. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  58. package/src/channels/shared/status-command.mjs +159 -0
  59. package/src/channels/shared/text-harness-bridge.mjs +86 -4
  60. package/src/channels/shared/workspace-command.mjs +20 -12
  61. package/src/channels/shared/workspace-session.mjs +30 -5
  62. package/src/channels/telegram/approval-card.mjs +379 -0
  63. package/src/channels/telegram/telegram-api.mjs +10 -1
  64. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  65. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  66. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -0,0 +1,48 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { sameWorkspacePath } from './default-workspace.mjs';
4
+ import { validateAgentPresetId } from './agent-preset.mjs';
5
+
6
+ /** Register a preset's group without changing any bot workspace or existing session binding. */
7
+ export async function ensurePresetWorkspace(harness, workspace, preset, catalog, options = {}) {
8
+ const id = validateAgentPresetId(preset);
9
+ if (
10
+ !id ||
11
+ typeof harness?.isUngroupedWorkspace !== 'function' ||
12
+ !(await harness.isUngroupedWorkspace(workspace))
13
+ )
14
+ return workspace;
15
+ const directory = join(workspace, 'presets', id);
16
+ await mkdir(directory, { recursive: true, mode: 0o700 });
17
+ const listing = await harness.rpc('workspace.list', {}, 30000, options);
18
+ if (!Array.isArray(listing?.items)) throw new Error('Harness returned an invalid workspace list');
19
+ let existing;
20
+ for (const item of listing.items) {
21
+ if (await sameWorkspacePath(item.path, directory)) {
22
+ existing = item;
23
+ break;
24
+ }
25
+ }
26
+ // A user may rename an automatically created group. Preserve that title.
27
+ if (existing && existing.title !== id) return directory;
28
+ const result = existing
29
+ ? { workspace: existing }
30
+ : await harness.rpc('workspace.create', { path: directory }, 30000, options);
31
+ if (!result?.workspace?.workspaceId) throw new Error('Harness returned an invalid workspace');
32
+ if (result.created === false && result.workspace.title !== id) return directory;
33
+ const label = catalog?.items.find((item) => item.id === id)?.label ?? id;
34
+ const title = listing.items.some(
35
+ (item) => item.title === label && item.workspaceId !== result.workspace.workspaceId,
36
+ )
37
+ ? `${label}(${id})`
38
+ : label;
39
+ if (result.workspace.title !== title) {
40
+ await harness.rpc(
41
+ 'workspace.rename',
42
+ { workspaceId: result.workspace.workspaceId, title },
43
+ 30000,
44
+ options,
45
+ );
46
+ }
47
+ return directory;
48
+ }
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
3
- import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
3
+ import { normalizeDiagnosticDetails, safeDiagnosticMessage } from './diagnostic-details.mjs';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  let installedDependencies;
@@ -27,13 +27,19 @@ function dependencies() {
27
27
  return installedDependencies;
28
28
  }
29
29
 
30
- /** Attach only safe facts; never copy QR contents, exception text or stack traces. */
30
+ /** Attach only safe facts: no QR contents, no stack traces.
31
+ * The deepest cause's message is included when it reads as plain technical
32
+ * text (see `safeDiagnosticMessage`); it is the only fact that separates
33
+ * `QRCode.toDataURL is not a function` from a zlib failure with the same shape. */
31
34
  export function qrEncodingError(cause) {
32
35
  if (cause?.name === 'AbortError') return cause;
33
36
  const evidence = extractConnectionEvidence(cause);
37
+ const leaf = evidence.chain.at(-1);
38
+ const causeMessage = safeDiagnosticMessage(leaf?.message);
34
39
  return connectionStageError(new Error('QR encoding failed', { cause }), 'qr.encode', undefined, {
35
40
  qrEncoder: 'qrcode', qrRenderer: 'png',
36
41
  errorTypes: evidence.errors.map(error => error.type),
42
+ ...(causeMessage ? { causeMessage } : {}),
37
43
  dependencies: dependencies(),
38
44
  });
39
45
  }
@@ -0,0 +1,159 @@
1
+ import { t } from './i18n.mjs';
2
+
3
+ /** Long enough to tell sessions apart in a chat, short enough to read. */
4
+ const SESSION_ID_DISPLAY_LENGTH = 12;
5
+
6
+ /**
7
+ * Optional /status fields must not hold the reply open when the Host is stuck.
8
+ * Three seconds is well above a healthy local RPC and short enough that the
9
+ * connection line is never buried behind a frozen Session/models read.
10
+ */
11
+ export const STATUS_FIELD_TIMEOUT_MS = 3_000;
12
+
13
+ function shortenedSessionId(sessionId) {
14
+ return sessionId.length > SESSION_ID_DISPLAY_LENGTH
15
+ ? `${sessionId.slice(0, SESSION_ID_DISPLAY_LENGTH)}…`
16
+ : sessionId;
17
+ }
18
+
19
+ /**
20
+ * The workspace the current conversation actually runs in: an explicit
21
+ * per-conversation pin when present, otherwise the bot-wide default.
22
+ */
23
+ function readWorkspace(harness, conversationKey) {
24
+ if (typeof harness?.currentConversationWorkspace === 'function'
25
+ && typeof conversationKey === 'string' && conversationKey) {
26
+ const workspace = harness.currentConversationWorkspace(conversationKey);
27
+ if (typeof workspace === 'string' && workspace) return workspace;
28
+ }
29
+ if (typeof harness?.currentWorkspace === 'function') {
30
+ const workspace = harness.currentWorkspace();
31
+ if (typeof workspace === 'string' && workspace) return workspace;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ async function readPreset(harness, options) {
37
+ if (typeof harness?.agentPresetSettings !== 'function') return null;
38
+ const settings = await harness.agentPresetSettings(options);
39
+ const preset = settings?.agentPreset;
40
+ if (typeof preset !== 'string' || !preset) return t('跟随 Host 默认');
41
+ const item = settings?.agentPresetCatalog?.items?.find((entry) => entry?.id === preset);
42
+ return item?.label ? `${item.label}(${preset})` : preset;
43
+ }
44
+
45
+ async function readModel(session, options) {
46
+ if (typeof session?.models !== 'function') return null;
47
+ const catalog = await session.models(options);
48
+ const current = catalog?.current;
49
+ if (typeof current?.provider !== 'string' || !current.provider
50
+ || typeof current?.model !== 'string' || !current.model) return null;
51
+ return `${current.provider}/${current.model}`;
52
+ }
53
+
54
+ async function readRunning(session, options) {
55
+ if (typeof session?.isRunning !== 'function') return false;
56
+ return (await session.isRunning(options)) === true;
57
+ }
58
+
59
+ /** Give the optional reads their own deadline, without cancelling the turn. */
60
+ function fieldReadOptions(signal, timeoutMs) {
61
+ const timeout = AbortSignal.timeout(timeoutMs);
62
+ return { signal: signal ? AbortSignal.any([signal, timeout]) : timeout };
63
+ }
64
+
65
+ /** A status field is optional: one failing read must not fail the command. */
66
+ async function settled(operation) {
67
+ try {
68
+ return await operation();
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * A status field is optional AND must not outlive its deadline.
76
+ *
77
+ * The abort signal alone is not enough: the real Host chain
78
+ * (`agentPresetSettings()` reads the preset directory before it re-checks the
79
+ * signal) can ignore it and never settle, which would hold the whole reply
80
+ * open. Race the read against its own timer so the deadline holds no matter
81
+ * how the underlying RPC behaves; the signal still lets cooperative readers
82
+ * cancel their work early.
83
+ */
84
+ function settledWithin(operation, timeoutMs) {
85
+ return new Promise((resolve) => {
86
+ let settledAlready = false;
87
+ const finish = (value) => {
88
+ if (settledAlready) return false;
89
+ settledAlready = true;
90
+ clearTimeout(timer);
91
+ resolve(value ?? null);
92
+ return true;
93
+ };
94
+ const timer = setTimeout(() => finish(null), timeoutMs);
95
+ timer.unref?.();
96
+ (async () => operation())().then(finish, () => finish(null));
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Render one readable /status reply for the text channels.
102
+ *
103
+ * The first line is the historical connection confirmation. Everything after
104
+ * it is best-effort: a workspace, session binding, model or Agent Preset that
105
+ * cannot be read is omitted (or explained) instead of turning the command into
106
+ * a failure. The running-task line appears only when this chat's bound session
107
+ * is actually running, so the common idle case stays short. Optional reads use
108
+ * a bounded signal ({@link STATUS_FIELD_TIMEOUT_MS}) so a frozen Host cannot
109
+ * make the command hang.
110
+ */
111
+ export async function runStatusCommand({
112
+ descriptor,
113
+ harness,
114
+ state,
115
+ conversationKey,
116
+ signal,
117
+ fieldTimeoutMs = STATUS_FIELD_TIMEOUT_MS,
118
+ } = {}) {
119
+ if (!harness || typeof harness.ensureRunning !== 'function') {
120
+ throw new TypeError('A Harness client with ensureRunning is required');
121
+ }
122
+ const options = signal ? { signal } : {};
123
+ await harness.ensureRunning(options);
124
+ const fieldTimeout = Number.isSafeInteger(fieldTimeoutMs) && fieldTimeoutMs > 0
125
+ ? fieldTimeoutMs
126
+ : STATUS_FIELD_TIMEOUT_MS;
127
+ const fieldOptions = fieldReadOptions(signal, fieldTimeout);
128
+
129
+ const label = descriptor?.label ?? 'Telegram';
130
+ const lines = [t('{label}机器人与 DeepSeek Harness 连接正常。', { label })];
131
+
132
+ const workspace = await settled(() => readWorkspace(harness, conversationKey));
133
+ if (workspace) lines.push(t('工作区:{workspace}', { workspace }));
134
+
135
+ const sessionId = await settled(async () => (typeof state?.sessionFor === 'function'
136
+ ? state.sessionFor(conversationKey)
137
+ : null));
138
+ const boundSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
139
+ lines.push(boundSessionId
140
+ ? t('绑定会话:{session}', { session: shortenedSessionId(boundSessionId) })
141
+ : t('绑定会话:未绑定(发送消息后自动创建)'));
142
+
143
+ const session = boundSessionId
144
+ ? await settled(() => (typeof harness.workspaceSession === 'function'
145
+ ? harness.workspaceSession(boundSessionId, conversationKey)
146
+ : null))
147
+ : null;
148
+ const [model, preset, running] = await Promise.all([
149
+ session ? settledWithin(() => readModel(session, fieldOptions), fieldTimeout) : null,
150
+ settledWithin(() => readPreset(harness, fieldOptions), fieldTimeout),
151
+ session ? settledWithin(() => readRunning(session, fieldOptions), fieldTimeout) : false,
152
+ ]);
153
+ if (model) lines.push(t('当前模型:{model}', { model }));
154
+ else if (!session) lines.push(t('当前模型:暂无(创建会话后显示)'));
155
+ if (preset) lines.push(t('Agent Preset(预设):{preset}', { preset }));
156
+ if (running === true) lines.push(t('运行中任务:有(发送 /stop 可停止)'));
157
+
158
+ return { message: lines.join('\n') };
159
+ }
@@ -14,6 +14,7 @@ import {
14
14
  enhanceContextContent,
15
15
  } from './context-enhancement.mjs';
16
16
  import { runWorkspaceCommand, workspaceSwitchFailureText } from './workspace-command.mjs';
17
+ import { runStatusCommand } from './status-command.mjs';
17
18
  import { runCompactCommand } from './compact-command.mjs';
18
19
  import { isClearCommand, runClearCommand } from './clear-command.mjs';
19
20
  import { isHistoryCommand, runHistoryCommand } from './history-command.mjs';
@@ -214,6 +215,9 @@ export class TextHarnessBridge {
214
215
  #workspaceCards = new Map();
215
216
  // Conversation key → the one picker card that is still authoritative there.
216
217
  #workspaceCardKeys = new Map();
218
+ // Optional channel-supplied approval card controller (see HarnessApprovalQueue's
219
+ // render hook). Null keeps every channel's existing plain-text approval flow.
220
+ #approvalCard;
217
221
  #contextHooks = null;
218
222
  // Delivery attempts per message id. A failed turn releases its `markSeen` so
219
223
  // the next poll can retry, and this counter is what keeps that from becoming
@@ -242,6 +246,8 @@ export class TextHarnessBridge {
242
246
  keepaliveIntervalMs = 4_000,
243
247
  interactionCard = null,
244
248
  workspaceCard = null,
249
+ approvalCard = null,
250
+ approvalTimeoutMs,
245
251
  contextHooks = null,
246
252
  autoSteerSameSender = false,
247
253
  autoSteerLimit = 0,
@@ -264,6 +270,7 @@ export class TextHarnessBridge {
264
270
  this.#keepaliveIntervalMs = keepaliveIntervalMs;
265
271
  this.#interactionCard = interactionCard ?? null;
266
272
  this.#workspaceCard = workspaceCard ?? null;
273
+ this.#approvalCard = approvalCard ?? null;
267
274
  // Opt-in follow-up lanes for channels whose groups run on rapid consecutive
268
275
  // posts: fold a same sender's burst into one dispatch, and steer that
269
276
  // sender's own mid-turn follow-ups into the in-flight turn instead of
@@ -287,6 +294,10 @@ export class TextHarnessBridge {
287
294
  this.#approvals = new HarnessApprovalQueue({
288
295
  label: descriptor.key,
289
296
  logger,
297
+ // Tests and hosts may shorten the approval deadline; the default stays.
298
+ ...(Number.isFinite(approvalTimeoutMs) && approvalTimeoutMs > 0
299
+ ? { approvalTimeoutMs }
300
+ : {}),
290
301
  });
291
302
  // A queued message lives only in #queues. If the process dies before its
292
303
  // turn runs the user has already been told it is queued, so the persisted
@@ -1125,8 +1136,14 @@ export class TextHarnessBridge {
1125
1136
  return;
1126
1137
  }
1127
1138
  if (!hasImages && !hasFiles && command === '/status') {
1128
- await this.#harness.ensureRunning({ signal: this.#signal });
1129
- await this.#bot.sendText(target, t('{label}机器人与 DeepSeek Harness 连接正常。', { label: this.#descriptor.label }));
1139
+ const status = await runStatusCommand({
1140
+ descriptor: this.#descriptor,
1141
+ harness: this.#harness,
1142
+ state: this.#state,
1143
+ conversationKey,
1144
+ signal: this.#signal,
1145
+ });
1146
+ await this.#bot.sendText(target, status.message);
1130
1147
  return;
1131
1148
  }
1132
1149
  const workspaceCommand = !hasImages && !hasFiles
@@ -1224,9 +1241,12 @@ export class TextHarnessBridge {
1224
1241
  if (message.kind === 'group') content = prependSpeakerLabel(content, message.speakerName);
1225
1242
  const snapshot = this.#acceptedMessageIds.get(messageId);
1226
1243
  let contextEnhanced = false;
1244
+ // contextSource() is enhancement-only: it is read here, under an enabled
1245
+ // snapshot, and nowhere else. The author record below reuses this read.
1246
+ let contextSource = null;
1227
1247
  if (snapshot) {
1228
1248
  const originalContent = content ?? text;
1229
- const contextSource = message.contextSource?.();
1249
+ contextSource = message.contextSource?.() ?? null;
1230
1250
  content = enhanceContextContent(originalContent, snapshot, () => ({
1231
1251
  channel: this.#descriptor.key,
1232
1252
  senderId,
@@ -1286,6 +1306,22 @@ export class TextHarnessBridge {
1286
1306
  // opened: the auto-steer lane keys its authorship decision off this
1287
1307
  // record, and the finally below retires it when the turn settles.
1288
1308
  this.#turnAuthors.set(conversationKey, { senderId, steered: 0, turnMessageId: messageId });
1309
+ // Persist who spoke here last, so a later describeConversation() can name
1310
+ // the sender of a group turn without replaying any message text. Channels
1311
+ // that own a different state store simply skip it.
1312
+ // The sender id and bot flag are always kept. A display name is kept only
1313
+ // when the channel already exposes it (Matrix speakerName) or context
1314
+ // enhancement read it above; a disabled enhancement never leaks names.
1315
+ try {
1316
+ await this.#state.rememberAuthor?.(conversationKey, {
1317
+ senderId,
1318
+ senderName: message.senderName ?? message.speakerName ?? contextSource?.senderName,
1319
+ senderUsername: message.senderUsername ?? contextSource?.senderUsername,
1320
+ isBot: message.senderIsBot === true,
1321
+ });
1322
+ } catch (error) {
1323
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] unable to remember the conversation author:`, error?.message ?? error);
1324
+ }
1289
1325
  // The prompt is about to enter the Harness inbox, which is itself durable.
1290
1326
  // Marking the entry submitted first means a crash after this point reports
1291
1327
  // the message instead of replaying a turn the Harness may already own.
@@ -1841,6 +1877,26 @@ export class TextHarnessBridge {
1841
1877
  // namespace before the question bookkeeping so a press can never touch it.
1842
1878
  const workspacePress = this.#workspaceCard?.parse?.(callback.data) ?? null;
1843
1879
  if (workspacePress) return this.#handleWorkspaceCardPress(callback, key, workspacePress);
1880
+ // Approval cards own their callback namespace; every other press keeps using
1881
+ // the question-card path below. The card acknowledges the press itself (the
1882
+ // ack must be the first round-trip), so this branch runs before any other
1883
+ // work in acceptCallback.
1884
+ if (this.#approvalCard && typeof this.#approvalCard.handlePress === 'function') {
1885
+ const handled = await this.#approvalCard.handlePress(callback, {
1886
+ bot: this.#bot,
1887
+ answer: (text) => this.#answerInteractionCallback(callback, text),
1888
+ submit: (approvalId, outcome, options) => (
1889
+ this.#approvals.submitByApprovalId(approvalId, outcome, options)
1890
+ ),
1891
+ }).catch((error) => {
1892
+ this.#logger.error?.(
1893
+ `[dsh-im:${this.#descriptor.key}] failed to handle an approval card press:`,
1894
+ error,
1895
+ );
1896
+ return false;
1897
+ });
1898
+ if (handled) return;
1899
+ }
1844
1900
  const pending = this.#pendingInteractions.get(key);
1845
1901
  const notice = (text) => this.#answerInteractionCallback(callback, text);
1846
1902
  if (!pending) return notice(t('该问题已处理,无需再次选择。'));
@@ -2083,11 +2139,37 @@ export class TextHarnessBridge {
2083
2139
  requiresMention,
2084
2140
  }) {
2085
2141
  if (interaction?.kind === 'approval') {
2142
+ const send = (text) => this.#bot.sendText(target, text);
2143
+ // Optional interactive-card presentation. The shared queue calls
2144
+ // `render(pending, send)` instead of the plain text when present and
2145
+ // `onResolved(text, outcome)` after any decision (button or typed reply).
2146
+ let cardContext = null;
2147
+ if (this.#approvalCard && typeof this.#approvalCard.createContext === 'function') {
2148
+ try {
2149
+ cardContext = this.#approvalCard.createContext({
2150
+ key,
2151
+ actor,
2152
+ target,
2153
+ send,
2154
+ bot: this.#bot,
2155
+ logger: this.#logger,
2156
+ });
2157
+ } catch (error) {
2158
+ this.#logger.warn?.(
2159
+ `[dsh-im:${this.#descriptor.key}] approval card unavailable; keeping the text approval:`,
2160
+ error?.message ?? error,
2161
+ );
2162
+ }
2163
+ }
2086
2164
  return this.#approvals.handleRequested(interaction, {
2087
2165
  key,
2088
2166
  actor,
2089
2167
  requiresMention,
2090
- send: (text) => this.#bot.sendText(target, text),
2168
+ send: typeof cardContext?.send === 'function' ? cardContext.send : send,
2169
+ ...(typeof cardContext?.render === 'function' ? { render: cardContext.render } : {}),
2170
+ ...(typeof cardContext?.onResolved === 'function'
2171
+ ? { onResolved: cardContext.onResolved }
2172
+ : {}),
2091
2173
  });
2092
2174
  }
2093
2175
  if (interaction?.kind !== 'question') return;
@@ -115,12 +115,7 @@ async function selectedWorkspacePath(value) {
115
115
  export async function workspacePathSnapshot(harness, { includeTitles = false, includeConversationDirectories = false, conversationKey, ...options } = {}) {
116
116
  const withEntries = includeTitles && typeof harness.listWorkspaceEntries === 'function';
117
117
  const listed = await (withEntries ? harness.listWorkspaceEntries(options) : harness.listWorkspaces(options));
118
- const currentValue = typeof harness?.currentConversationWorkspace === 'function'
119
- && typeof conversationKey === 'string' && conversationKey
120
- ? harness.currentConversationWorkspace(conversationKey)
121
- : typeof harness?.currentWorkspace === 'function'
122
- ? harness.currentWorkspace()
123
- : null;
118
+ const currentValue = await conversationSessionWorkspace(harness, conversationKey, options);
124
119
  const current = await existingWorkspacePath(currentValue);
125
120
  const entries = await Promise.all((Array.isArray(listed) ? listed : []).map(async (item) => ({
126
121
  path: await existingWorkspacePath(withEntries ? item?.path : item),
@@ -207,10 +202,21 @@ async function runWorkspaceListCommand(match, harness) {
207
202
  return workspaceListingCommand(harness, { includeConversationDirectories });
208
203
  }
209
204
 
210
- async function conversationEffectiveWorkspace(harness, conversationKey) {
211
- if (typeof harness?.currentConversationWorkspace !== 'function'
212
- || typeof conversationKey !== 'string' || !conversationKey) return null;
213
- const [current] = await existingWorkspacePaths([harness.currentConversationWorkspace(conversationKey)]);
205
+ export async function conversationSessionWorkspace(harness, conversationKey, options = {}) {
206
+ if (typeof conversationKey === 'string' && conversationKey) {
207
+ if (typeof harness?.resolveConversationWorkspace === 'function') {
208
+ return harness.resolveConversationWorkspace(conversationKey, options);
209
+ }
210
+ if (typeof harness?.currentConversationWorkspace === 'function') {
211
+ return harness.currentConversationWorkspace(conversationKey);
212
+ }
213
+ }
214
+ return harness?.currentWorkspace?.() ?? null;
215
+ }
216
+
217
+ async function conversationEffectiveWorkspace(harness, conversationKey, options) {
218
+ if (typeof conversationKey !== 'string' || !conversationKey) return null;
219
+ const [current] = await existingWorkspacePaths([await conversationSessionWorkspace(harness, conversationKey, options)]);
214
220
  harness.assertWorkspaceScope?.();
215
221
  return current ?? null;
216
222
  }
@@ -220,7 +226,7 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
220
226
  // With no explicit selector the listing follows the conversation's effective
221
227
  // workspace, so /conv B makes /sessionlist list B instead of the bot default.
222
228
  if (options.conversationKey) {
223
- const effective = await conversationEffectiveWorkspace(harness, options.conversationKey);
229
+ const effective = await conversationEffectiveWorkspace(harness, options.conversationKey, options);
224
230
  if (effective) return { workspace: effective };
225
231
  }
226
232
  if (typeof harness?.currentWorkspace !== 'function') {
@@ -235,7 +241,9 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
235
241
  if (typeof harness?.listWorkspaces !== 'function') {
236
242
  return { error: t('当前机器人暂不支持按序号选择工作区。') };
237
243
  }
238
- const { paths } = await workspacePathSnapshot(harness, options);
244
+ // Explicit workspace numbers must keep the bot-wide /workspacelist order;
245
+ // only a missing selector follows the bound conversation's actual group.
246
+ const { paths } = await workspacePathSnapshot(harness, { ...options, conversationKey: undefined });
239
247
  const position = Number(selector);
240
248
  if (!Number.isSafeInteger(position) || position < 1 || position > paths.length) {
241
249
  return { error: t('工作区序号不存在,请先执行 /workspacelist。') };
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { withSessionBindingLock } from './session-binding-lock.mjs';
2
3
  import { initialSessionTitle } from './session-title.mjs';
3
4
  import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
@@ -133,12 +134,36 @@ export async function askInWorkspaceSession({
133
134
  if (dsBotSessionId) {
134
135
  throw Object.assign(new Error('DS Bot 的当前会话不可用。'), { code: 'ds-bot-unavailable' });
135
136
  }
136
- sessionId = await createSession(harness, {
137
- conversationKey: key,
138
- ...(createOptions ?? {}),
139
- });
137
+ // Name the Session here and bind it *before* creating it. Prompt
138
+ // assembly runs inside creation, and a subscriber that resolves the
139
+ // conversation by session id can only answer if the conversation owns
140
+ // the id by then.
141
+ // A Harness that accepts a caller-chosen id lets the binding exist
142
+ // before the Session does; anything else keeps the old order.
143
+ const plannedSessionId = harness?.canChooseSessionId === true ? `session-${randomUUID()}` : null;
144
+ const previousSessionId = plannedSessionId === null ? null : state.sessionFor(key) ?? null;
145
+ if (plannedSessionId !== null && await state.setSession(key, plannedSessionId) === false) return null;
146
+ try {
147
+ sessionId = await createSession(harness, {
148
+ conversationKey: key,
149
+ ...(plannedSessionId === null ? {} : { sessionId: plannedSessionId }),
150
+ ...(createOptions ?? {}),
151
+ });
152
+ } catch (error) {
153
+ // The binding must not outlive a Session that was never created, and a
154
+ // failed replacement must leave the previous binding in place.
155
+ if (plannedSessionId !== null) {
156
+ if (previousSessionId === null) await state.clearSession?.(key);
157
+ else await state.setSession(key, previousSessionId);
158
+ }
159
+ throw error;
160
+ }
140
161
  diagnostic.sessionId = sessionId;
141
- if (await state.setSession(key, sessionId) === false) return null;
162
+ if (plannedSessionId === null) {
163
+ if (await state.setSession(key, sessionId) === false) return null;
164
+ } else if (sessionId !== plannedSessionId && await state.setSession(key, sessionId) === false) {
165
+ return null;
166
+ }
142
167
  // Binding committed: capture the conversation's effective-workspace
143
168
  // generation together with the session, so the prompt below is fenced
144
169
  // against a conversation switch that only commits after the bind.