@xmanrui/dsh-im 5.2.0 → 5.4.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 (65) hide show
  1. package/THIRD_PARTY_NOTICES.md +209 -0
  2. package/docs/client-integration.md +8 -4
  3. package/lib/client.js +1988 -250
  4. package/lib/index.js +327 -321
  5. package/package.json +1 -1
  6. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  7. package/plugin-src/client/connection-error.js +2 -1
  8. package/plugin-src/client/delivery-settings.js +21 -1
  9. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  10. package/plugin-src/client/ds-bot-avatar.js +55 -0
  11. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  12. package/plugin-src/client/ds-bot-settings.js +194 -0
  13. package/plugin-src/client/global-settings.js +2 -1
  14. package/plugin-src/client/i18n.js +67 -1
  15. package/plugin-src/client/index.js +49 -18
  16. package/plugin-src/client/plugin-page.js +39 -17
  17. package/plugin-src/client/sidebar-settings.js +129 -0
  18. package/plugin-src/client/styles.js +33 -5
  19. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  20. package/plugin-src/host/channels/dingtalk/rpc.mjs +5 -1
  21. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  22. package/plugin-src/host/channels/feishu/rpc.mjs +5 -1
  23. package/plugin-src/host/channels/qq/production.mjs +2 -1
  24. package/plugin-src/host/channels/qq/rpc.mjs +5 -1
  25. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  26. package/plugin-src/host/channels/shared/production.mjs +7 -1
  27. package/plugin-src/host/channels/slack/production.mjs +2 -1
  28. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  29. package/plugin-src/host/channels/telegram/production.mjs +2 -0
  30. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  31. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  32. package/plugin-src/host/channels/wecom/rpc.mjs +5 -1
  33. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  34. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  35. package/plugin-src/host/channels/weixin/rpc.mjs +3 -2
  36. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  37. package/plugin-src/host/channels/whatsapp/rpc.mjs +5 -1
  38. package/plugin-src/host/delivery-adapter.mjs +89 -9
  39. package/plugin-src/host/delivery-rpc.mjs +33 -1
  40. package/plugin-src/host/delivery-service.mjs +70 -1
  41. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  42. package/plugin-src/host/ds-bot-client.mjs +74 -0
  43. package/plugin-src/host/index.mjs +12 -1
  44. package/plugin-src/host/sidebar-settings.mjs +113 -0
  45. package/src/channels/feishu/feishu-cards.mjs +11 -7
  46. package/src/channels/imessage/imessage-api.mjs +67 -2
  47. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  48. package/src/channels/shared/connection-error.mjs +5 -5
  49. package/src/channels/shared/diagnostic-details.mjs +15 -1
  50. package/src/channels/shared/group-history-store.mjs +26 -0
  51. package/src/channels/shared/i18n-en/diagnostics.mjs +5 -0
  52. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  53. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  54. package/src/channels/shared/qr-encoding-error.mjs +39 -0
  55. package/src/channels/shared/session-binding-lock.mjs +2 -0
  56. package/src/channels/shared/workspace-session.mjs +5 -1
  57. package/src/channels/telegram/config-store.mjs +5 -1
  58. package/src/channels/telegram/group-triggers.mjs +229 -0
  59. package/src/channels/telegram/telegram-api.mjs +12 -0
  60. package/src/channels/telegram/telegram-controller.mjs +110 -1
  61. package/src/channels/telegram/telegram-runtime.mjs +15 -2
  62. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  63. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  64. package/src/channels/wecom/wecom-runtime.mjs +12 -1
  65. package/src/channels/weixin/connection-error.mjs +1 -0
@@ -53,6 +53,67 @@ function appleScriptString(value) {
53
53
  return JSON.stringify(String(value));
54
54
  }
55
55
 
56
+ // macOS 26 (Tahoe) stopped populating message.text for received iMessages: the
57
+ // body is only stored in message.attributedBody, an NSArchiver typedstream blob
58
+ // (`streamtyped` + archived NSAttributedString). These constants describe the
59
+ // inline-string run we need to read from that archive.
60
+ const ATTRIBUTED_BODY_STRING_CLASS = Buffer.from('NSString', 'utf8');
61
+ const ATTRIBUTED_BODY_STRING_TAG = 0x2b; // '+': inline NSString payload follows
62
+ // Attachment-only messages carry U+FFFC (object replacement character) instead
63
+ // of text. The channel is text-only, so such runs must keep normalizing to null.
64
+ const OBJECT_REPLACEMENT_CHARACTER = '\ufffc';
65
+
66
+ // Apple NXTypedStream integer encoding: a signed byte is a literal length,
67
+ // 0x81/0x82/0x83 introduce a little-endian 2/4/8-byte length.
68
+ function readTypedStreamLength(buffer, offset) {
69
+ if (offset >= buffer.length) return null;
70
+ const tag = buffer[offset];
71
+ let cursor = offset + 1;
72
+ let length;
73
+ if (tag === 0x81) {
74
+ if (cursor + 2 > buffer.length) return null;
75
+ length = buffer.readInt16LE(cursor);
76
+ cursor += 2;
77
+ } else if (tag === 0x82) {
78
+ if (cursor + 4 > buffer.length) return null;
79
+ length = buffer.readInt32LE(cursor);
80
+ cursor += 4;
81
+ } else if (tag === 0x83) {
82
+ if (cursor + 8 > buffer.length) return null;
83
+ const value = buffer.readBigInt64LE(cursor);
84
+ if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) return null;
85
+ length = Number(value);
86
+ cursor += 8;
87
+ } else {
88
+ length = tag > 0x7f ? tag - 0x100 : tag;
89
+ }
90
+ if (!Number.isInteger(length) || length < 0 || cursor + length > buffer.length) return null;
91
+ return { length, offset: cursor };
92
+ }
93
+
94
+ // Accepts either the hex string selected via hex(m.attributedBody) or the raw blob.
95
+ export function decodeAttributedBodyText(value) {
96
+ const buffer = Buffer.isBuffer(value)
97
+ ? value
98
+ : typeof value === 'string' && value.trim() ? Buffer.from(value.trim(), 'hex') : null;
99
+ if (!buffer?.length) return null;
100
+ const marker = buffer.indexOf(ATTRIBUTED_BODY_STRING_CLASS);
101
+ if (marker < 0) return null;
102
+ let tagIndex = marker + ATTRIBUTED_BODY_STRING_CLASS.length;
103
+ while (tagIndex < buffer.length && buffer[tagIndex] !== ATTRIBUTED_BODY_STRING_TAG) tagIndex += 1;
104
+ if (tagIndex >= buffer.length) return null;
105
+ const run = readTypedStreamLength(buffer, tagIndex + 1);
106
+ if (!run || run.length === 0) return null;
107
+ let text;
108
+ try {
109
+ text = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(run.offset, run.offset + run.length));
110
+ } catch {
111
+ return null;
112
+ }
113
+ const stripped = text.replaceAll(OBJECT_REPLACEMENT_CHARACTER, '').trim();
114
+ return stripped || null;
115
+ }
116
+
56
117
  export function normalizeIMessageTarget(value) {
57
118
  return normalizeChatGuid(value);
58
119
  }
@@ -62,7 +123,8 @@ export function normalizeIMessage(value, { botId } = {}) {
62
123
  if (value.serviceName !== undefined && value.serviceName !== 'iMessage') return null;
63
124
  const guid = cleanString(value.guid ?? value.id);
64
125
  const chatGuid = cleanString(value.chatGuid ?? value.chat_guid);
65
- const text = cleanString(value.text);
126
+ const text = cleanString(value.text)
127
+ ?? decodeAttributedBodyText(value.attributedBodyHex ?? value.attributedBody);
66
128
  const sender = cleanString(value.sender ?? value.handle_id);
67
129
  if (!guid || !chatGuid || !text || !sender) return null;
68
130
  if (text.startsWith(IMESSAGE_BOT_REPLY_PREFIX)) return null;
@@ -127,7 +189,10 @@ export class MacOSMessagesApi {
127
189
  const chatFilter = chatGuid ? ` AND c.guid = ${sqlString(normalizeChatGuid(chatGuid))}` : '';
128
190
  // Messages delivers self-chat back as an incoming copy. Read that copy once,
129
191
  // keeping all outgoing rows excluded, and filter bot replies by their marker.
192
+ // macOS 26 (Tahoe) stores received iMessage bodies only in attributedBody, so
193
+ // accept either text column and decode the blob when text is empty.
130
194
  const query = `SELECT m.ROWID AS rowid, m.guid AS guid, m.text AS text,
195
+ hex(m.attributedBody) AS attributedBodyHex,
131
196
  h.id AS sender, c.guid AS chatGuid, c.service_name AS serviceName,
132
197
  m.is_from_me AS isFromMe,
133
198
  datetime((m.date / 1000000000) + 978307200, 'unixepoch') AS receivedAt
@@ -136,7 +201,7 @@ export class MacOSMessagesApi {
136
201
  JOIN chat c ON c.ROWID = cmj.chat_id
137
202
  LEFT JOIN handle h ON h.ROWID = m.handle_id
138
203
  WHERE m.ROWID > ${cursor} AND m.is_from_me = 0
139
- AND m.text IS NOT NULL AND m.text != ''
204
+ AND ((m.text IS NOT NULL AND m.text != '') OR m.attributedBody IS NOT NULL)
140
205
  AND c.service_name = 'iMessage'${chatFilter}
141
206
  ORDER BY m.ROWID ASC LIMIT ${boundedLimit};`;
142
207
  try {
@@ -23,6 +23,7 @@ import {
23
23
  validateAccessPolicy,
24
24
  } from './access-policy.mjs';
25
25
  import { CONNECTION_TEST_STATE_IDENTITY } from './connection-test.mjs';
26
+ import { SESSION_BINDING_STATE_IDENTITY } from './session-binding-lock.mjs';
26
27
  import {
27
28
  DEFAULT_CONTEXT_ENHANCEMENT_CONFIG,
28
29
  normalizeContextEnhancementConfig,
@@ -39,7 +40,9 @@ import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
39
40
  import { configValidationError, withConfigResource } from './config-read-error.mjs';
40
41
 
41
42
  const DELIVERY_DOCUMENT_VERSION = 2;
42
- export const CURRENT_DOCUMENT_VERSION = 3;
43
+ const SESSION_SYNC_DOCUMENT_VERSION = 3;
44
+ const DS_BOT_DOCUMENT_VERSION = 4;
45
+ export const CURRENT_DOCUMENT_VERSION = 5;
43
46
  const EMPTY_DOCUMENT = Object.freeze({ version: 1, workspaces: Object.freeze({}) });
44
47
 
45
48
  function invalidWorkspaceConfig(field, issue) {
@@ -211,7 +214,7 @@ function normalizeDeliveryTargets(value, { version } = {}) {
211
214
  }
212
215
  const normalized = normalizeDeliveryTarget(candidate, {
213
216
  targetId,
214
- allowSessionSync: version >= CURRENT_DOCUMENT_VERSION,
217
+ allowSessionSync: version >= SESSION_SYNC_DOCUMENT_VERSION,
215
218
  });
216
219
  const { targetId: _targetId, ...stored } = normalized;
217
220
  normalizedTargets[targetId] = stored;
@@ -244,9 +247,29 @@ function normalizeAccessPolicies(value, workspaces) {
244
247
  return accessPolicies;
245
248
  }
246
249
 
250
+ function normalizeDsBotBindings(value) {
251
+ const bindings = Object.create(null);
252
+ if (value === undefined) return bindings;
253
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
254
+ return invalidWorkspaceConfig('dsBotBindings', 'expected-object');
255
+ }
256
+ try {
257
+ for (const [botId, conversations] of Object.entries(value)) {
258
+ botIdOf(botId);
259
+ if (!conversations || typeof conversations !== 'object' || Array.isArray(conversations)) throw new TypeError();
260
+ bindings[botId] = Object.fromEntries(Object.entries(conversations).map(([key, dsBotId]) => (
261
+ [conversationKeyOf(key), dsBotId === null ? null : botIdOf(dsBotId)]
262
+ )));
263
+ }
264
+ } catch {
265
+ return invalidWorkspaceConfig('dsBotBindings', 'invalid-binding');
266
+ }
267
+ return bindings;
268
+ }
269
+
247
270
  function normalizeDocument(value) {
248
271
  if (!value || typeof value !== 'object' || Array.isArray(value)) return invalidWorkspaceConfig('$', 'expected-object');
249
- if (![1, DELIVERY_DOCUMENT_VERSION, CURRENT_DOCUMENT_VERSION].includes(value.version)) return invalidWorkspaceConfig('version', 'unsupported-version');
272
+ if (![1, DELIVERY_DOCUMENT_VERSION, SESSION_SYNC_DOCUMENT_VERSION, DS_BOT_DOCUMENT_VERSION, CURRENT_DOCUMENT_VERSION].includes(value.version)) return invalidWorkspaceConfig('version', 'unsupported-version');
250
273
  if (!value.workspaces || typeof value.workspaces !== 'object' || Array.isArray(value.workspaces)) return invalidWorkspaceConfig('workspaces', 'expected-object');
251
274
  const workspaces = {};
252
275
  for (const [index, [botId, workspace]] of Object.entries(value.workspaces).entries()) {
@@ -298,6 +321,7 @@ function normalizeDocument(value) {
298
321
  }
299
322
  if (value.version === 1 && value.deliveryTargets !== undefined) return invalidWorkspaceConfig('deliveryTargets', 'unexpected-field');
300
323
  const deliveryTargets = normalizeDeliveryTargets(value.deliveryTargets, { version: value.version });
324
+ const dsBotBindings = normalizeDsBotBindings(value.dsBotBindings);
301
325
  const aliases = Object.create(null);
302
326
  if (value.aliases && typeof value.aliases === 'object' && !Array.isArray(value.aliases)) {
303
327
  for (const [botId, alias] of Object.entries(value.aliases)) {
@@ -330,6 +354,7 @@ function normalizeDocument(value) {
330
354
  models,
331
355
  contextEnhancement,
332
356
  deliveryTargets,
357
+ dsBotBindings,
333
358
  accessPolicies,
334
359
  aliases,
335
360
  busyMessageModes,
@@ -344,11 +369,13 @@ function storedDocument({
344
369
  models,
345
370
  contextEnhancement,
346
371
  deliveryTargets,
372
+ dsBotBindings,
347
373
  accessPolicies,
348
374
  aliases,
349
375
  busyMessageModes,
350
376
  }) {
351
377
  const document = { version, workspaces };
378
+ if (Object.keys(dsBotBindings).length > 0) document.dsBotBindings = dsBotBindings;
352
379
  if (Object.keys(busyMessageModes).length > 0) document.busyMessageModes = busyMessageModes;
353
380
  if (Object.keys(aliases).length > 0) document.aliases = aliases;
354
381
  if (Object.keys(conversationWorkspaces).length > 0) {
@@ -414,6 +441,7 @@ export class BotWorkspaceStore {
414
441
  #busyMessageModes = Object.create(null);
415
442
  #contextEnhancement = {};
416
443
  #deliveryTargets = Object.create(null);
444
+ #dsBotBindings = Object.create(null);
417
445
  #accessPolicies = Object.create(null);
418
446
  #conversationWorkspaces = Object.create(null);
419
447
  #generations = new Map();
@@ -446,6 +474,7 @@ export class BotWorkspaceStore {
446
474
  this.#busyMessageModes = normalized.busyMessageModes;
447
475
  this.#contextEnhancement = normalized.contextEnhancement;
448
476
  this.#deliveryTargets = normalized.deliveryTargets;
477
+ this.#dsBotBindings = normalized.dsBotBindings;
449
478
  this.#accessPolicies = normalized.accessPolicies;
450
479
  this.#conversationWorkspaces = normalized.conversationWorkspaces;
451
480
  } catch (error) {
@@ -458,6 +487,7 @@ export class BotWorkspaceStore {
458
487
  this.#busyMessageModes = Object.create(null);
459
488
  this.#contextEnhancement = {};
460
489
  this.#deliveryTargets = Object.create(null);
490
+ this.#dsBotBindings = Object.create(null);
461
491
  this.#accessPolicies = Object.create(null);
462
492
  this.#conversationWorkspaces = Object.create(null);
463
493
  }
@@ -688,6 +718,49 @@ export class BotWorkspaceStore {
688
718
  return this.#generations.get(botIdOf(botId)) ?? null;
689
719
  }
690
720
 
721
+ dsBotBindingFor(botId, conversationKey) {
722
+ const dsBotId = this.#dsBotBindings[botId]?.[conversationKey];
723
+ return this.has(botId) && dsBotId ? { botId, conversationKey, dsBotId } : null;
724
+ }
725
+
726
+ listDsBotBindings(botId) {
727
+ return Object.entries(this.#dsBotBindings).flatMap(([id, conversations]) => (
728
+ this.has(id) && (botId === undefined || botId === id)
729
+ ? Object.entries(conversations).filter(([, dsBotId]) => dsBotId !== null)
730
+ .map(([conversationKey, dsBotId]) => ({ botId: id, conversationKey, dsBotId }))
731
+ : []
732
+ ));
733
+ }
734
+
735
+ dsBotConversationKeys(botId) {
736
+ return this.has(botId) ? Object.keys(this.#dsBotBindings[botId] ?? {}) : [];
737
+ }
738
+
739
+ async setDsBotBinding(botId, conversationKey, dsBotId) {
740
+ const id = botIdOf(botId);
741
+ const key = conversationKeyOf(conversationKey);
742
+ const selected = dsBotId === null ? null : botIdOf(dsBotId);
743
+ return this.#enqueue(id, async () => {
744
+ if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
745
+ const conversations = { ...this.#dsBotBindings[id] };
746
+ if (selected !== null && (conversations[key] || Object.values(conversations).includes(selected))) {
747
+ throw deliveryTargetError('ds-bot-binding-conflict', 'DS Bot or private chat is already bound');
748
+ }
749
+ // Keep a confirmed private-chat key after unbinding so it can be selected
750
+ // again without keeping its old DS Bot session mapping alive.
751
+ conversations[key] = selected;
752
+ const next = { ...this.#dsBotBindings, [id]: conversations };
753
+ if (!Object.keys(conversations).length) delete next[id];
754
+ await this.#persist(
755
+ this.#contextEnhancement, this.#deliveryTargets, CURRENT_DOCUMENT_VERSION,
756
+ this.#accessPolicies, this.#aliases, this.#conversationWorkspaces, this.#busyMessageModes, next,
757
+ );
758
+ this.#dsBotBindings = next;
759
+ this.#version = CURRENT_DOCUMENT_VERSION;
760
+ return this.dsBotBindingFor(id, key);
761
+ });
762
+ }
763
+
691
764
  async whenIdle() {
692
765
  await this.#writeQueue;
693
766
  }
@@ -1359,10 +1432,11 @@ export class BotWorkspaceStore {
1359
1432
  const hadMessageMode = Object.hasOwn(this.#busyMessageModes, id);
1360
1433
  const hadContextEnhancement = Object.hasOwn(this.#contextEnhancement, id);
1361
1434
  const hadDeliveryTargets = Object.hasOwn(this.#deliveryTargets, id);
1435
+ const hadDsBotBindings = Object.hasOwn(this.#dsBotBindings, id);
1362
1436
  const hadAccessPolicy = Object.hasOwn(this.#accessPolicies, id);
1363
1437
  const hadConversationWorkspaces = Object.hasOwn(this.#conversationWorkspaces, id);
1364
1438
  const needsCleanup = hadWorkspace || hadPreset || hadModel || hadAlias || hadContextEnhancement
1365
- || hadDeliveryTargets || hadAccessPolicy || hadConversationWorkspaces || hadMessageMode
1439
+ || hadDeliveryTargets || hadDsBotBindings || hadAccessPolicy || hadConversationWorkspaces || hadMessageMode
1366
1440
  || this.#dirtyRemovals.has(id);
1367
1441
  delete this.#workspaces[id];
1368
1442
  delete this.#agentPresets[id];
@@ -1371,6 +1445,7 @@ export class BotWorkspaceStore {
1371
1445
  delete this.#busyMessageModes[id];
1372
1446
  delete this.#contextEnhancement[id];
1373
1447
  delete this.#deliveryTargets[id];
1448
+ delete this.#dsBotBindings[id];
1374
1449
  delete this.#accessPolicies[id];
1375
1450
  delete this.#conversationWorkspaces[id];
1376
1451
  this.#generations.delete(id);
@@ -1410,6 +1485,7 @@ export class BotWorkspaceStore {
1410
1485
  aliases = this.#aliases,
1411
1486
  conversationWorkspaces = this.#conversationWorkspaces,
1412
1487
  busyMessageModes = this.#busyMessageModes,
1488
+ dsBotBindings = this.#dsBotBindings,
1413
1489
  ) {
1414
1490
  await writeStoredDocument(this.#path, storedDocument({
1415
1491
  version,
@@ -1419,6 +1495,7 @@ export class BotWorkspaceStore {
1419
1495
  models: this.#models,
1420
1496
  contextEnhancement,
1421
1497
  deliveryTargets,
1498
+ dsBotBindings,
1422
1499
  accessPolicies,
1423
1500
  aliases,
1424
1501
  busyMessageModes,
@@ -1434,6 +1511,7 @@ export class BotWorkspaceStore {
1434
1511
  || Object.keys(this.#busyMessageModes).length > 0
1435
1512
  || Object.keys(this.#contextEnhancement).length > 0
1436
1513
  || Object.keys(this.#deliveryTargets).length > 0
1514
+ || Object.keys(this.#dsBotBindings).length > 0
1437
1515
  || Object.keys(this.#accessPolicies).length > 0
1438
1516
  || Object.keys(this.#conversationWorkspaces).length > 0) {
1439
1517
  await this.#persist();
@@ -1564,12 +1642,18 @@ export function observeBotWorkspaceRemovals(
1564
1642
 
1565
1643
  export function createBotWorkspaceScope(
1566
1644
  harness,
1567
- { botId, workspaces, state, agentPresetCatalog } = {},
1645
+ { botId, workspaces, state, agentPresetCatalog, dsBot } = {},
1568
1646
  ) {
1569
1647
  if (!harness || !workspaces || !state) throw new TypeError('harness, workspaces, and state are required');
1570
1648
  const incarnation = workspaces.incarnationFor(botId);
1571
1649
  const isCurrentScope = () => workspaces.has(botId)
1572
1650
  && workspaces.incarnationFor(botId) === incarnation;
1651
+ const dsBinding = (key) => workspaces.dsBotBindingFor?.(botId, key);
1652
+ const assertNoDsBinding = (key) => {
1653
+ if (dsBinding(key)) {
1654
+ throw deliveryTargetError('ds-bot-bound', '请先在“绑定bot”中解除绑定,再切换会话或工作目录。');
1655
+ }
1656
+ };
1573
1657
  const presetSettings = async (catalog = agentPresetCatalog) => {
1574
1658
  let normalizedCatalog;
1575
1659
  try {
@@ -1694,6 +1778,27 @@ export function createBotWorkspaceScope(
1694
1778
 
1695
1779
  const scopedHarness = new Proxy(harness, {
1696
1780
  get(target, property) {
1781
+ if (property === 'resolveDsBotSession') {
1782
+ return async (key) => {
1783
+ assertCurrentBotScope(isCurrentScope);
1784
+ const binding = dsBinding(key);
1785
+ if (!binding) return null;
1786
+ if (!dsBot) throw deliveryTargetError('ds-bot-unavailable', 'DS Bot 当前不可用,请检查插件状态。');
1787
+ const bot = await dsBot.resolve(binding.dsBotId);
1788
+ if (!(await target.sessionExists(bot.sessionId))) {
1789
+ throw deliveryTargetError('ds-bot-not-found', 'DS Bot 的当前会话不可用。');
1790
+ }
1791
+ assertCurrentBotScope(isCurrentScope);
1792
+ if (dsBinding(key)?.dsBotId !== binding.dsBotId) throw workspaceSessionStale('DS Bot binding changed');
1793
+ if (state.sessionFor(key) !== bot.sessionId) await state.setSession(key, bot.sessionId);
1794
+ sessionGenerations.set(bot.sessionId, {
1795
+ generation: workspaces.generationFor(botId),
1796
+ conversationKey: key,
1797
+ conversationGeneration: currentConversationGeneration(key),
1798
+ });
1799
+ return bot.sessionId;
1800
+ };
1801
+ }
1697
1802
  if (property === 'agentPresetSettings') {
1698
1803
  return async (options = {}) => {
1699
1804
  options?.signal?.throwIfAborted();
@@ -1780,6 +1885,9 @@ export function createBotWorkspaceScope(
1780
1885
  }
1781
1886
  if (property === 'switchWorkspace') {
1782
1887
  return (workspace) => {
1888
+ if (workspaces.listDsBotBindings(botId).length > 0) {
1889
+ throw deliveryTargetError('ds-bot-bound', '请先解除 DS Bot 绑定,再切换机器人工作目录。');
1890
+ }
1783
1891
  if (!isCurrentScope()) {
1784
1892
  const error = new Error('找不到要修改的机器人。');
1785
1893
  error.code = 'workspace-bot-not-found';
@@ -1820,6 +1928,7 @@ export function createBotWorkspaceScope(
1820
1928
  }
1821
1929
  if (property === 'switchConversationWorkspace') {
1822
1930
  return (conversationKey, workspace) => {
1931
+ assertNoDsBinding(conversationKey);
1823
1932
  if (!isCurrentScope()) {
1824
1933
  const error = new Error('找不到要修改的机器人。');
1825
1934
  error.code = 'workspace-bot-not-found';
@@ -1841,6 +1950,7 @@ export function createBotWorkspaceScope(
1841
1950
  }
1842
1951
  if (property === 'clearConversationWorkspace') {
1843
1952
  return (conversationKey) => {
1953
+ assertNoDsBinding(conversationKey);
1844
1954
  if (!isCurrentScope()) {
1845
1955
  const error = new Error('找不到要修改的机器人。');
1846
1956
  error.code = 'workspace-bot-not-found';
@@ -1860,6 +1970,7 @@ export function createBotWorkspaceScope(
1860
1970
  }
1861
1971
  if (property === 'bindWorkspaceSession') {
1862
1972
  return async (conversationKey, sessionId) => {
1973
+ assertNoDsBinding(conversationKey);
1863
1974
  if (typeof conversationKey !== 'string' || !conversationKey
1864
1975
  || typeof sessionId !== 'string' || !sessionId) {
1865
1976
  throw new TypeError('conversationKey and sessionId are required');
@@ -1934,6 +2045,7 @@ export function createBotWorkspaceScope(
1934
2045
  if (property === 'createSession') {
1935
2046
  return async (options = {}) => {
1936
2047
  const { inheritBotModel = true, conversationKey, ...createOptions } = options;
2048
+ assertNoDsBinding(conversationKey);
1937
2049
  // /conv publishes its generation before path validation enters the
1938
2050
  // bot queue. Wait for both phases before pairing a workspace with its
1939
2051
  // generation; otherwise a new session can carry a new fence but old cwd.
@@ -2016,7 +2128,9 @@ export function createBotWorkspaceScope(
2016
2128
  : null;
2017
2129
  // Copy provenance into the immutable handle, but retain it for a later
2018
2130
  // setSession (notably /model, which binds after asynchronous selection).
2131
+ const dsBotId = dsBinding(conversationKey)?.dsBotId;
2019
2132
  const isCurrentSession = () => isCurrentScope()
2133
+ && dsBinding(conversationKey)?.dsBotId === dsBotId
2020
2134
  && generation === workspaces.generationFor(botId)
2021
2135
  && !conversationGenerationIsStale(conversationKey, conversationGeneration);
2022
2136
  const invokeCurrentSession = async (method, args, action) => {
@@ -2067,6 +2181,7 @@ export function createBotWorkspaceScope(
2067
2181
  },
2068
2182
  } : {}),
2069
2183
  selectModel(...args) {
2184
+ if (dsBotId) throw deliveryTargetError('ds-bot-bound', '请在 DS Bot 中修改模型。');
2070
2185
  return invokeCurrentSession('selectSessionModel', args, 'model selection');
2071
2186
  },
2072
2187
  isRunning(...args) {
@@ -2089,12 +2204,19 @@ export function createBotWorkspaceScope(
2089
2204
  return invokeStartedSessionMutation('executeCommand', args, 'command execution');
2090
2205
  },
2091
2206
  } : {}),
2092
- ask(...args) {
2207
+ async ask(...args) {
2093
2208
  if (!isCurrentSession()) {
2094
2209
  throw workspaceSessionStale(
2095
2210
  'The bot workspace changed before this prompt started.',
2096
2211
  );
2097
2212
  }
2213
+ if (dsBotId) {
2214
+ const bot = await dsBot?.resolve(dsBotId);
2215
+ if (!bot) throw deliveryTargetError('ds-bot-unavailable', 'DS Bot 当前不可用。');
2216
+ if (bot.sessionId !== sessionId || !isCurrentSession()) {
2217
+ throw workspaceSessionStale('DS Bot changed before this prompt started.');
2218
+ }
2219
+ }
2098
2220
  return target.ask(sessionId, ...args);
2099
2221
  },
2100
2222
  });
@@ -2138,7 +2260,7 @@ export function createBotWorkspaceScope(
2138
2260
  });
2139
2261
  const scopedState = new Proxy(state, {
2140
2262
  get(target, property) {
2141
- if (property === CONNECTION_TEST_STATE_IDENTITY) return target;
2263
+ if (property === CONNECTION_TEST_STATE_IDENTITY || property === SESSION_BINDING_STATE_IDENTITY) return target;
2142
2264
  if (property === 'sessionFor') {
2143
2265
  return (key, ...args) => {
2144
2266
  if (!isCurrentScope()) return null;
@@ -2164,6 +2286,7 @@ export function createBotWorkspaceScope(
2164
2286
  }
2165
2287
  if (property === 'setSession') {
2166
2288
  return (key, sessionId, ...args) => {
2289
+ if (dsBinding(key) && target.sessionFor(key) !== sessionId) assertNoDsBinding(key);
2167
2290
  const entry = sessionGenerations.get(sessionId);
2168
2291
  if (!isCurrentScope() || generationIsStale(entry, key)) {
2169
2292
  return false;
@@ -2171,6 +2294,12 @@ export function createBotWorkspaceScope(
2171
2294
  return target.setSession(key, sessionId, ...args);
2172
2295
  };
2173
2296
  }
2297
+ if (property === 'clearSession') {
2298
+ return (key, ...args) => {
2299
+ assertNoDsBinding(key);
2300
+ return target.clearSession(key, ...args);
2301
+ };
2302
+ }
2174
2303
  const value = Reflect.get(target, property, target);
2175
2304
  return typeof value === 'function' ? value.bind(target) : value;
2176
2305
  },
@@ -1,13 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import packageInfo from '../../../package.json' with { type: 'json' };
3
- import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
3
+ import { DIAGNOSTIC_ERROR_TYPES, normalizeDiagnosticDetails } from './diagnostic-details.mjs';
4
4
  import { t } from './i18n.mjs';
5
5
 
6
6
  const reported = new WeakMap();
7
7
  const lastReport = new WeakMap();
8
8
  const stages = new WeakMap();
9
9
  const OWNED_REASONS = { 'harness-interaction-timeout': 'timeout', 'harness-response-invalid': 'invalid-response', 'connect-timeout': 'timeout', 'telegram-timeout': 'timeout', 'cli-timeout': 'timeout', 'provider-timeout': 'timeout', 'telegram-response-invalid': 'invalid-response', 'office-protocol-mismatch': 'invalid-response' };
10
- const STANDARD_NAMES = new Set(['Error', 'TypeError', 'SyntaxError', 'AggregateError', 'DOMException', 'AxiosError', 'TimeoutError', 'AbortError']);
11
10
  const KNOWN_MESSAGES = {
12
11
  'discord-401': 'Discord Bot Token 无效,请重新填写。',
13
12
  'discord-intents': 'Discord Gateway Intents 配置不正确,请检查 Developer Portal 的 Bot 设置。',
@@ -36,7 +35,7 @@ export function connectionErrorChain(error) {
36
35
  export function extractConnectionEvidence(error) {
37
36
  const { chain, truncated } = connectionErrorChain(error);
38
37
  const errors = chain.map(e => ({
39
- type: STANDARD_NAMES.has(e.name) ? e.name : 'Error',
38
+ type: DIAGNOSTIC_ERROR_TYPES.has(e.name) ? e.name : 'Error',
40
39
  // Host RPC adapters carry safe diagnostic facts without the original Error graph.
41
40
  ...normalizeDiagnosticDetails({
42
41
  reason: e.details?.reason, reasons: e.details?.reasons,
@@ -98,9 +97,9 @@ export async function atConnectionStage(stage, operation, resource) {
98
97
  catch (error) { throw connectionStageError(error, stage, resource); }
99
98
  }
100
99
 
101
- export function connectionStageError(cause, stage, resource) {
100
+ export function connectionStageError(cause, stage, resource, details = {}) {
102
101
  if (!cause || typeof cause !== 'object') cause = new Error('Operation failed');
103
- if (!stages.has(cause)) stages.set(cause, normalizeDiagnosticDetails({ stage, resource }));
102
+ if (!stages.has(cause)) stages.set(cause, normalizeDiagnosticDetails({ ...details, stage, resource }));
104
103
  return cause;
105
104
  }
106
105
 
@@ -117,6 +116,7 @@ export function diagnosticRpcResult(diagnostics, cause, result, context) {
117
116
  }
118
117
 
119
118
  export function connectionHint(details) {
119
+ if (details.stage === 'qr.encode') return t('本机二维码图片生成失败,请重试;若持续失败,请复制诊断信息并检查 DSH 运行环境。');
120
120
  const r = details.reason;
121
121
  if (r === 'multiple-causes') return t('检测到多个底层原因,请展开诊断详情逐项检查。');
122
122
  if (['ENOTFOUND', 'EAI_AGAIN'].includes(r)) return t('服务域名解析失败,请检查运行 DSH 的机器的 DNS 和网络设置。');
@@ -19,6 +19,10 @@ const REASONS = new Set([
19
19
  'CERT_HAS_EXPIRED', 'CERT_NOT_YET_VALID', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN',
20
20
  'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'ERR_TLS_CERT_ALTNAME_INVALID', 'ERR_SSL_WRONG_VERSION_NUMBER',
21
21
  'ENOENT', 'EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'ENOTDIR', 'EISDIR', 'EBUSY', 'EIO', 'EXDEV', 'EMFILE', 'ENFILE', 'EEXIST',
22
+ 'ERR_INVALID_ARG_TYPE', 'ERR_INVALID_ARG_VALUE', 'ERR_OUT_OF_RANGE', 'ERR_BUFFER_OUT_OF_BOUNDS',
23
+ 'ERR_ZLIB_INITIALIZATION_FAILED', 'ERR_STREAM_DESTROYED', 'ERR_STREAM_PREMATURE_CLOSE',
24
+ 'Z_STREAM_ERROR', 'Z_DATA_ERROR', 'Z_MEM_ERROR', 'Z_BUF_ERROR', 'Z_VERSION_ERROR',
25
+ 'MODULE_NOT_FOUND', 'ERR_MODULE_NOT_FOUND',
22
26
  'unknown', 'multiple-causes', 'timeout', 'http-error', 'provider-rejected', 'invalid-response', 'ERR_PROXY_CONNECTION_FAILED', 'ERR_TLS_HANDSHAKE_TIMEOUT', 'ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR', 'ERR_NETWORK_ACCESS_DENIED', 'AUTHENTICATIONFAILED', 'EAUTH', 'invalid-json', 'invalid-config', 'read-only',
23
27
  ]);
24
28
  const RESOURCES = new Set(['credential-store', 'account-config', 'account-state', 'workspace-config', 'workspace-directory']);
@@ -30,6 +34,10 @@ const RPC_METHODS = new Set([
30
34
  const TRANSPORTS = new Set(['host-api', 'http', 'websocket']);
31
35
  const SUBMISSION_STATES = new Set(['not-submitted', 'accepted', 'unknown']);
32
36
  const CONFIG_FILES = new Set(['config.json', 'workspaces.json']);
37
+ export const DIAGNOSTIC_ERROR_TYPES = new Set([
38
+ 'Error', 'TypeError', 'RangeError', 'ReferenceError', 'SyntaxError', 'AggregateError',
39
+ 'DOMException', 'AxiosError', 'TimeoutError', 'AbortError',
40
+ ]);
33
41
  export const CONFIG_ISSUE_LABELS = Object.freeze({
34
42
  'expected-object': '应为 JSON 对象。',
35
43
  'expected-array': '应为 JSON 数组。',
@@ -57,6 +65,12 @@ export function normalizeDiagnosticDetails(value) {
57
65
  if (allowed.has(value[field])) result[field] = value[field];
58
66
  }
59
67
  if (DIAGNOSTIC_CHANNELS.includes(value.channel)) result.channel = value.channel;
68
+ if (Array.isArray(value.errorTypes)) {
69
+ const errorTypes = [...new Set(value.errorTypes.filter(type => DIAGNOSTIC_ERROR_TYPES.has(type)))];
70
+ if (errorTypes.length) result.errorTypes = errorTypes;
71
+ }
72
+ if (value.qrEncoder === 'qrcode') result.qrEncoder = value.qrEncoder;
73
+ if (value.qrRenderer === 'png') result.qrRenderer = value.qrRenderer;
60
74
  if (Array.isArray(value.reasons)) {
61
75
  const reasons = [...new Set(value.reasons.filter(v => REASONS.has(v) && !['unknown', 'multiple-causes'].includes(v)))].slice(0, 16);
62
76
  if (reasons.length) result.reasons = reasons;
@@ -68,7 +82,7 @@ export function normalizeDiagnosticDetails(value) {
68
82
  if (['ilinkai.weixin.qq.com', 'oapi.dingtalk.com', 'api.dingtalk.com', 'api.telegram.org', 'discord.com', 'slack.com', 'open.feishu.cn', 'qyapi.weixin.qq.com'].includes(value.host)) result.host = value.host;
69
83
  if (value.dependencies && typeof value.dependencies === 'object') {
70
84
  const dependencies = {};
71
- for (const name of ['dingtalkStream', 'axios', 'httpsProxyAgent', 'agentBase']) {
85
+ for (const name of ['dingtalkStream', 'axios', 'httpsProxyAgent', 'agentBase', 'qrcode', 'pngjs', 'zlib']) {
72
86
  const version = value.dependencies[name];
73
87
  if (typeof version === 'string' && /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(version) && version.length <= 80) dependencies[name] = version;
74
88
  }
@@ -320,6 +320,32 @@ export class GroupHistoryStore {
320
320
  coverage: 'Only messages actually received by this plugin; not complete platform history.' };
321
321
  }
322
322
 
323
+ /**
324
+ * Groups this channel has archived, newest activity first.
325
+ *
326
+ * Used by channel settings that are scoped per chat (Telegram's per-group
327
+ * reply rules) so the panel can offer real chat IDs with their titles.
328
+ */
329
+ async listGroups({ channel } = {}) {
330
+ await this.ready();
331
+ if (!GROUP_HISTORY_CHANNELS.includes(channel)) return [];
332
+ const rows = this.#db.prepare(`SELECT g.platform_group_id AS chat_id, g.name AS title,
333
+ g.last_received_at AS last_received_at, g.capability AS capability,
334
+ (SELECT m.sender_name FROM messages m WHERE m.group_id = g.id
335
+ ORDER BY m.sent_at DESC, m.received_at DESC LIMIT 1) AS last_sender_name
336
+ FROM groups g WHERE g.channel = ? ORDER BY coalesce(g.last_received_at, 0) DESC`).all(channel);
337
+ return rows.map((row) => ({
338
+ chatId: String(row.chat_id),
339
+ title: typeof row.title === 'string' && row.title ? row.title : null,
340
+ // The archive stores no chat type; the platform reported a group.
341
+ type: null,
342
+ lastSeenAt: Number.isSafeInteger(row.last_received_at) && row.last_received_at > 0
343
+ ? new Date(row.last_received_at).toISOString() : null,
344
+ lastSenderName: typeof row.last_sender_name === 'string' && row.last_sender_name
345
+ ? row.last_sender_name : null,
346
+ }));
347
+ }
348
+
323
349
  async materialize(groupId, attachmentId, workspace) {
324
350
  await this.ready();
325
351
  if (this.#settingsError) throw invalid(this.#settingsError);
@@ -1,4 +1,9 @@
1
1
  export default Object.freeze({
2
+ '异常类型': 'Exception types',
3
+ '二维码编码器': 'QR encoder',
4
+ '二维码图片格式': 'QR image format',
5
+ '本机二维码图片生成失败,请重试;若持续失败,请复制诊断信息并检查 DSH 运行环境。':
6
+ 'The QR-code image could not be generated locally. Retry; if it keeps failing, copy the diagnostics and check the DSH runtime environment.',
2
7
  '准备会话': 'Prepare session',
3
8
  '准备消息': 'Prepare message',
4
9
  '建立交互通道': 'Open interaction channel',
@@ -392,6 +392,7 @@ export default {
392
392
  '🔐 工具审批': '🔐 Tool approval',
393
393
  // feishu/feishu-cards.mjs — question card
394
394
  '❓ 请补充信息{progress}': '❓ Please provide more information{progress}',
395
+ '选择 {number}': 'Select {number}',
395
396
  // feishu/bridge.mjs — deferred delivery terminal statuses
396
397
  '后台任务已结束({reason}),没有可推送的最终结果。':
397
398
  'The background task has finished ({reason}); there is no final result to deliver.',
@@ -1,5 +1,9 @@
1
1
  // English translations (wecom area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ '▣ 第 {segment} 段 · 任务仍在进行,继续见下一条 ↓':
4
+ '▣ Part {segment} · Task still running, continuing in the next message ↓',
5
+ '继续执行中…': 'Continuing…',
6
+ '仍在执行中…': 'Still working…',
3
7
  '/menu 或 /m 打开可点击的功能菜单': '/menu or /m Open the interactive menu',
4
8
  '保持当前': 'Keep current',
5
9
  '会话': 'Session',
@@ -0,0 +1,39 @@
1
+ import { createRequire } from 'node:module';
2
+ import { connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
3
+ import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ let installedDependencies;
7
+
8
+ function resolvedPackage(name, from) {
9
+ try {
10
+ const path = from.resolve(`${name}/package.json`);
11
+ return { version: from(path)?.version, require: createRequire(path) };
12
+ } catch {
13
+ // Diagnostics must not replace the original encoding failure.
14
+ return undefined;
15
+ }
16
+ }
17
+
18
+ function dependencies() {
19
+ if (!installedDependencies) {
20
+ const qrcode = resolvedPackage('qrcode', require);
21
+ // Resolve from qrcode so nested installations report the PNG library it uses.
22
+ const pngjs = qrcode && resolvedPackage('pngjs', qrcode.require);
23
+ installedDependencies = Object.freeze(normalizeDiagnosticDetails({ dependencies: {
24
+ qrcode: qrcode?.version, pngjs: pngjs?.version, zlib: process.versions.zlib,
25
+ } }).dependencies ?? {});
26
+ }
27
+ return installedDependencies;
28
+ }
29
+
30
+ /** Attach only safe facts; never copy QR contents, exception text or stack traces. */
31
+ export function qrEncodingError(cause) {
32
+ if (cause?.name === 'AbortError') return cause;
33
+ const evidence = extractConnectionEvidence(cause);
34
+ return connectionStageError(new Error('QR encoding failed', { cause }), 'qr.encode', undefined, {
35
+ qrEncoder: 'qrcode', qrRenderer: 'png',
36
+ errorTypes: evidence.errors.map(error => error.type),
37
+ dependencies: dependencies(),
38
+ });
39
+ }
@@ -1,4 +1,5 @@
1
1
  const bindingLocks = new WeakMap();
2
+ export const SESSION_BINDING_STATE_IDENTITY = Symbol('session-binding-state-identity');
2
3
 
3
4
  function stateLocks(state) {
4
5
  let locks = bindingLocks.get(state);
@@ -21,6 +22,7 @@ export async function withSessionBindingLock(state, key, operation) {
21
22
  if (typeof key !== 'string' || !key) throw new TypeError('conversation key is required');
22
23
  if (typeof operation !== 'function') throw new TypeError('operation is required');
23
24
 
25
+ state = state[SESSION_BINDING_STATE_IDENTITY] ?? state;
24
26
  const locks = stateLocks(state);
25
27
  const previous = locks.get(key) ?? Promise.resolve();
26
28
  let release;