@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
@@ -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';
@@ -75,6 +76,7 @@ import {
75
76
  } from './message-failure.mjs';
76
77
  import { logDeliveryFailure } from './delivery-failure-log.mjs';
77
78
  import { beginStatusReaction } from './status-reaction.mjs';
79
+ import { startNewConversation } from './new-command.mjs';
78
80
 
79
81
  /** Cap and TTL for the in-memory workspace-picker snapshots behind button presses. */
80
82
  const MAX_WORKSPACE_CARDS = 50;
@@ -213,6 +215,9 @@ export class TextHarnessBridge {
213
215
  #workspaceCards = new Map();
214
216
  // Conversation key → the one picker card that is still authoritative there.
215
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;
216
221
  #contextHooks = null;
217
222
  // Delivery attempts per message id. A failed turn releases its `markSeen` so
218
223
  // the next poll can retry, and this counter is what keeps that from becoming
@@ -241,6 +246,8 @@ export class TextHarnessBridge {
241
246
  keepaliveIntervalMs = 4_000,
242
247
  interactionCard = null,
243
248
  workspaceCard = null,
249
+ approvalCard = null,
250
+ approvalTimeoutMs,
244
251
  contextHooks = null,
245
252
  autoSteerSameSender = false,
246
253
  autoSteerLimit = 0,
@@ -263,6 +270,7 @@ export class TextHarnessBridge {
263
270
  this.#keepaliveIntervalMs = keepaliveIntervalMs;
264
271
  this.#interactionCard = interactionCard ?? null;
265
272
  this.#workspaceCard = workspaceCard ?? null;
273
+ this.#approvalCard = approvalCard ?? null;
266
274
  // Opt-in follow-up lanes for channels whose groups run on rapid consecutive
267
275
  // posts: fold a same sender's burst into one dispatch, and steer that
268
276
  // sender's own mid-turn follow-ups into the in-flight turn instead of
@@ -286,6 +294,10 @@ export class TextHarnessBridge {
286
294
  this.#approvals = new HarnessApprovalQueue({
287
295
  label: descriptor.key,
288
296
  logger,
297
+ // Tests and hosts may shorten the approval deadline; the default stays.
298
+ ...(Number.isFinite(approvalTimeoutMs) && approvalTimeoutMs > 0
299
+ ? { approvalTimeoutMs }
300
+ : {}),
289
301
  });
290
302
  // A queued message lives only in #queues. If the process dies before its
291
303
  // turn runs the user has already been told it is queued, so the persisted
@@ -1124,8 +1136,14 @@ export class TextHarnessBridge {
1124
1136
  return;
1125
1137
  }
1126
1138
  if (!hasImages && !hasFiles && command === '/status') {
1127
- await this.#harness.ensureRunning({ signal: this.#signal });
1128
- 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);
1129
1147
  return;
1130
1148
  }
1131
1149
  const workspaceCommand = !hasImages && !hasFiles
@@ -1141,7 +1159,7 @@ export class TextHarnessBridge {
1141
1159
  return;
1142
1160
  }
1143
1161
  if (!hasImages && !hasFiles && command === '/new') {
1144
- await this.#state.clearSession(conversationKey);
1162
+ const receipt = await startNewConversation({ state: this.#state, harness: this.#harness, key: conversationKey });
1145
1163
  if (this.#contextHooks?.onSessionCleared) {
1146
1164
  try {
1147
1165
  await this.#contextHooks.onSessionCleared(conversationKey);
@@ -1150,7 +1168,7 @@ export class TextHarnessBridge {
1150
1168
  this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] failed to reset context anchors after /new:`, error?.message ?? error);
1151
1169
  }
1152
1170
  }
1153
- await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
1171
+ await this.#bot.sendText(target, `${receipt}\n${t('请发送你的问题。')}`);
1154
1172
  return;
1155
1173
  }
1156
1174
  const compactCommand = !hasImages && !hasFiles
@@ -1223,9 +1241,12 @@ export class TextHarnessBridge {
1223
1241
  if (message.kind === 'group') content = prependSpeakerLabel(content, message.speakerName);
1224
1242
  const snapshot = this.#acceptedMessageIds.get(messageId);
1225
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;
1226
1247
  if (snapshot) {
1227
1248
  const originalContent = content ?? text;
1228
- const contextSource = message.contextSource?.();
1249
+ contextSource = message.contextSource?.() ?? null;
1229
1250
  content = enhanceContextContent(originalContent, snapshot, () => ({
1230
1251
  channel: this.#descriptor.key,
1231
1252
  senderId,
@@ -1285,6 +1306,22 @@ export class TextHarnessBridge {
1285
1306
  // opened: the auto-steer lane keys its authorship decision off this
1286
1307
  // record, and the finally below retires it when the turn settles.
1287
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
+ }
1288
1325
  // The prompt is about to enter the Harness inbox, which is itself durable.
1289
1326
  // Marking the entry submitted first means a crash after this point reports
1290
1327
  // the message instead of replaying a turn the Harness may already own.
@@ -1840,6 +1877,26 @@ export class TextHarnessBridge {
1840
1877
  // namespace before the question bookkeeping so a press can never touch it.
1841
1878
  const workspacePress = this.#workspaceCard?.parse?.(callback.data) ?? null;
1842
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
+ }
1843
1900
  const pending = this.#pendingInteractions.get(key);
1844
1901
  const notice = (text) => this.#answerInteractionCallback(callback, text);
1845
1902
  if (!pending) return notice(t('该问题已处理,无需再次选择。'));
@@ -2082,11 +2139,37 @@ export class TextHarnessBridge {
2082
2139
  requiresMention,
2083
2140
  }) {
2084
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
+ }
2085
2164
  return this.#approvals.handleRequested(interaction, {
2086
2165
  key,
2087
2166
  actor,
2088
2167
  requiresMention,
2089
- 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
+ : {}),
2090
2173
  });
2091
2174
  }
2092
2175
  if (interaction?.kind !== 'question') return;
@@ -112,18 +112,18 @@ async function selectedWorkspacePath(value) {
112
112
  }
113
113
  }
114
114
 
115
- export async function workspacePathSnapshot(harness, { includeTitles = false, ...options } = {}) {
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?.currentWorkspace === 'function'
119
- ? harness.currentWorkspace()
120
- : null;
118
+ const currentValue = await conversationSessionWorkspace(harness, conversationKey, options);
121
119
  const current = await existingWorkspacePath(currentValue);
122
120
  const entries = await Promise.all((Array.isArray(listed) ? listed : []).map(async (item) => ({
123
121
  path: await existingWorkspacePath(withEntries ? item?.path : item),
124
122
  title: withEntries ? safeDisplayText(item?.title) : '',
125
123
  })));
126
- const paths = [...new Set([...(current ? [current] : []), ...entries.map((item) => item.path).filter(Boolean)])];
124
+ const directoryPaths = new Set(harness.conversationDirectoryPaths?.() ?? []);
125
+ const paths = [...new Set([...(current ? [current] : []), ...entries.map((item) => item.path).filter(Boolean)])]
126
+ .filter((path) => includeConversationDirectories || path === current || !directoryPaths.has(path));
127
127
  const titles = {};
128
128
  if (includeTitles) {
129
129
  for (const item of entries) {
@@ -162,12 +162,14 @@ export function splitWorkspaceCommandMessage(message) {
162
162
  * channel without an interactive picker keeps exactly what it always showed;
163
163
  * `listing` is the machine-readable half a channel may render as a picker.
164
164
  */
165
- async function workspaceListingCommand(harness) {
165
+ async function workspaceListingCommand(harness, { includeConversationDirectories = false } = {}) {
166
166
  if (typeof harness?.listWorkspaces !== 'function') {
167
167
  return commandResult(t('当前机器人暂不支持列出工作区。'));
168
168
  }
169
169
  try {
170
- const { current, paths, titles } = await workspacePathSnapshot(harness, { includeTitles: true });
170
+ const { current, paths, titles } = await workspacePathSnapshot(harness, {
171
+ includeTitles: true, includeConversationDirectories,
172
+ });
171
173
  if (paths.length === 0) {
172
174
  return commandResult(t('当前 Harness Host 上没有仍然存在的已登记工作区。'));
173
175
  }
@@ -195,14 +197,26 @@ async function workspaceListingCommand(harness) {
195
197
  }
196
198
 
197
199
  async function runWorkspaceListCommand(match, harness) {
198
- if (match[1]?.trim()) return commandResult(t('用法:/workspacelist'));
199
- return workspaceListingCommand(harness);
200
+ const includeConversationDirectories = match[1]?.trim().toLowerCase() === 'all';
201
+ if (match[1]?.trim() && !includeConversationDirectories) return commandResult(t('用法:/workspacelist'));
202
+ return workspaceListingCommand(harness, { includeConversationDirectories });
200
203
  }
201
204
 
202
- async function conversationEffectiveWorkspace(harness, conversationKey) {
203
- if (typeof harness?.currentConversationWorkspace !== 'function'
204
- || typeof conversationKey !== 'string' || !conversationKey) return null;
205
- 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)]);
206
220
  harness.assertWorkspaceScope?.();
207
221
  return current ?? null;
208
222
  }
@@ -212,7 +226,7 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
212
226
  // With no explicit selector the listing follows the conversation's effective
213
227
  // workspace, so /conv B makes /sessionlist list B instead of the bot default.
214
228
  if (options.conversationKey) {
215
- const effective = await conversationEffectiveWorkspace(harness, options.conversationKey);
229
+ const effective = await conversationEffectiveWorkspace(harness, options.conversationKey, options);
216
230
  if (effective) return { workspace: effective };
217
231
  }
218
232
  if (typeof harness?.currentWorkspace !== 'function') {
@@ -227,7 +241,9 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
227
241
  if (typeof harness?.listWorkspaces !== 'function') {
228
242
  return { error: t('当前机器人暂不支持按序号选择工作区。') };
229
243
  }
230
- 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 });
231
247
  const position = Number(selector);
232
248
  if (!Number.isSafeInteger(position) || position < 1 || position > paths.length) {
233
249
  return { error: t('工作区序号不存在,请先执行 /workspacelist。') };
@@ -475,6 +491,7 @@ async function runConversationWorkspaceCommand(command, harness, conversationKey
475
491
  try {
476
492
  let selected = argument;
477
493
  if (/^\d+$/u.test(argument)) {
494
+ // Match the ordering shown by /workspacelist, /ws and bare /conv.
478
495
  const { paths } = await workspacePathSnapshot(harness);
479
496
  const position = Number(argument);
480
497
  if (!Number.isSafeInteger(position) || position < 1 || position > paths.length) {
@@ -516,6 +533,10 @@ export function workspaceSwitchFailureText(error) {
516
533
 
517
534
  export async function runWorkspaceCommand(text, harness, conversationKey) {
518
535
  if (!isWorkspaceCommand(text)) return null;
536
+ const config = harness.conversationDirectoryConfig?.();
537
+ if (config?.enabled === true && /^(?:\/(?:workspace|ws|conv|conversation|thread))(?:\s|$)/iu.test(text.trim())) {
538
+ return { message: '', messages: [] };
539
+ }
519
540
  const command = text.trim();
520
541
  const threadMatch = THREAD_WORKSPACE_COMMAND.exec(command);
521
542
  if (threadMatch) {
@@ -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.