@xmanrui/dsh-im 4.35.1 → 4.36.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 (65) hide show
  1. package/PROACTIVE_DELIVERY.en.md +50 -0
  2. package/PROACTIVE_DELIVERY.md +22 -0
  3. package/README.en.md +3 -1
  4. package/README.md +3 -1
  5. package/lib/client.js +30 -8
  6. package/lib/index.js +309 -309
  7. package/package.json +3 -3
  8. package/plugin-src/client/connection-error.js +2 -1
  9. package/plugin-src/host/channels/dingtalk/production.mjs +1 -1
  10. package/plugin-src/host/channels/feishu/production.mjs +4 -2
  11. package/plugin-src/host/channels/matrix/production.mjs +1 -1
  12. package/plugin-src/host/channels/qq/production.mjs +1 -1
  13. package/plugin-src/host/channels/shared/production.mjs +1 -1
  14. package/plugin-src/host/channels/slack/production.mjs +1 -1
  15. package/plugin-src/host/channels/wecom/production.mjs +1 -1
  16. package/plugin-src/host/channels/wecom-app/production.mjs +1 -1
  17. package/plugin-src/host/channels/weixin/production.mjs +1 -1
  18. package/plugin-src/host/channels/whatsapp/production.mjs +1 -1
  19. package/plugin-src/host/delivery-adapter.mjs +60 -12
  20. package/plugin-src/host/delivery-service.mjs +127 -1
  21. package/plugin-src/host/delivery-suggestions.mjs +2 -1
  22. package/plugin-src/host/harness-connection.mjs +3 -7
  23. package/plugin-src/host/index.mjs +5 -2
  24. package/plugin-src/host/modern-harness-api.mjs +139 -4
  25. package/src/channels/dingtalk/dingtalk-bridge.mjs +6 -0
  26. package/src/channels/dingtalk/dingtalk-controller.mjs +14 -0
  27. package/src/channels/dingtalk/dingtalk-runtime.mjs +10 -0
  28. package/src/channels/discord/discord-runtime.mjs +13 -0
  29. package/src/channels/feishu/bridge.mjs +30 -13
  30. package/src/channels/feishu/external-consumer.mjs +118 -0
  31. package/src/channels/feishu/feishu-runtime.mjs +72 -3
  32. package/src/channels/feishu/history-reader.mjs +92 -0
  33. package/src/channels/feishu/multi-bot-controller.mjs +130 -2
  34. package/src/channels/feishu/nearby-history.mjs +72 -0
  35. package/src/channels/feishu/plugin-config-store.mjs +1 -0
  36. package/src/channels/matrix/matrix-controller.mjs +9 -0
  37. package/src/channels/matrix/matrix-runtime.mjs +14 -0
  38. package/src/channels/qq/qq-bridge.mjs +6 -0
  39. package/src/channels/qq/qq-controller.mjs +14 -0
  40. package/src/channels/qq/qq-runtime.mjs +10 -0
  41. package/src/channels/shared/connection-error.mjs +1 -0
  42. package/src/channels/shared/diagnostic-details.mjs +7 -1
  43. package/src/channels/shared/harness-approval.mjs +84 -7
  44. package/src/channels/shared/harness-client.mjs +51 -40
  45. package/src/channels/shared/i18n-en/diagnostics.mjs +3 -0
  46. package/src/channels/shared/i18n-en/shared-c.mjs +3 -0
  47. package/src/channels/shared/message-failure.mjs +1 -1
  48. package/src/channels/shared/text-harness-bridge.mjs +6 -0
  49. package/src/channels/shared/token-bot-controller.mjs +16 -0
  50. package/src/channels/slack/manifest.mjs +1 -0
  51. package/src/channels/slack/slack-api.mjs +7 -0
  52. package/src/channels/slack/slack-controller.mjs +14 -0
  53. package/src/channels/slack/slack-runtime.mjs +12 -0
  54. package/src/channels/telegram/telegram-runtime.mjs +10 -0
  55. package/src/channels/wecom/wecom-bridge.mjs +6 -0
  56. package/src/channels/wecom/wecom-controller.mjs +14 -0
  57. package/src/channels/wecom/wecom-runtime.mjs +10 -0
  58. package/src/channels/wecom-app/wecom-app-bridge.mjs +6 -0
  59. package/src/channels/wecom-app/wecom-app-controller.mjs +14 -0
  60. package/src/channels/wecom-app/wecom-app-runtime.mjs +10 -0
  61. package/src/channels/weixin/weixin-bridge.mjs +6 -0
  62. package/src/channels/weixin/weixin-controller.mjs +14 -0
  63. package/src/channels/weixin/weixin-runtime.mjs +10 -0
  64. package/src/channels/whatsapp/whatsapp-controller.mjs +14 -0
  65. package/src/channels/whatsapp/whatsapp-runtime.mjs +10 -0
@@ -0,0 +1,92 @@
1
+ import { readNearbyHistory } from './nearby-history.mjs';
2
+ import { normalizeExternalText } from './external-consumer.mjs';
3
+
4
+ function refuse(code) { throw Object.assign(new Error(code), { code }); }
5
+ function identifier(value) {
6
+ return typeof value === 'string' && value.length > 0 && value.length <= 512;
7
+ }
8
+
9
+ function check(response) {
10
+ if ([230027, 99991672, 99991679].includes(response?.code)) refuse('history-permission-denied');
11
+ if (response?.code) refuse('history-unavailable');
12
+ }
13
+
14
+ async function checkedSdkRead(operation, signal) {
15
+ let response;
16
+ try { response = await operation(); }
17
+ catch (error) {
18
+ signal?.throwIfAborted();
19
+ if (error?.name === 'AbortError') throw error;
20
+ if (error?.code === 'ABORT_ERR' || error?.code === 'ERR_CANCELED') refuse('cancelled');
21
+ // The SDK rejects HTTP 403 before returning the provider's JSON payload.
22
+ // Never expose its raw Axios error (which can contain credential headers).
23
+ check(error?.response?.data);
24
+ refuse('history-unavailable');
25
+ }
26
+ signal?.throwIfAborted();
27
+ check(response);
28
+ return response;
29
+ }
30
+
31
+ // Application-defined checked read: destination is derived from an authenticated source.
32
+ // Lark has Chat/time-range listing and Thread listing, not a native around-message API.
33
+ export async function readExternalHistory(client, identity, route, query, signal) {
34
+ if (!route || !identifier(route.messageId) || !identifier(route.conversationId)
35
+ || !identifier(route.actorId) || ['threadId', 'rootId', 'parentId'].some(key => route[key] !== undefined && !identifier(route[key])) || !['group', 'nearby', 'thread'].includes(query?.scope)
36
+ || !Number.isInteger(query.limit) || query.limit < 1 || query.limit > 20
37
+ || (query.cursor !== undefined && (typeof query.cursor !== 'string' || !query.cursor || query.cursor.length > 4096)))
38
+ refuse('bad-request');
39
+ if (query.scope === 'nearby' && [query.beforeCount ?? 10, query.afterCount ?? 5]
40
+ .some(value => !Number.isInteger(value) || value < 0 || value > 20)) refuse('bad-request');
41
+ signal?.throwIfAborted();
42
+ const reference = await checkedSdkRead(() => client.im.v1.message.get({ path: { message_id: route.messageId }, params: { with_sender_name: true } }, { signal }), signal);
43
+ signal?.throwIfAborted();
44
+ const source = (Array.isArray(reference?.data?.items) ? reference.data.items : []).find(item => item?.message_id === route.messageId);
45
+ if (!source || source.deleted || source.chat_id !== route.conversationId
46
+ || source.sender?.sender_type !== 'user' || source.sender?.id_type !== 'open_id'
47
+ || source.sender?.id !== route.actorId || (source.thread_id || undefined) !== route.threadId
48
+ || (source.root_id || undefined) !== route.rootId || (source.parent_id || undefined) !== route.parentId)
49
+ refuse('stale-route');
50
+ if (query.scope === 'thread' && !route.threadId) refuse('thread-unavailable');
51
+ signal?.throwIfAborted();
52
+ const seconds = Math.floor(Number(source.create_time) / 1000);
53
+ if (!Number.isFinite(seconds) || seconds <= 0) refuse('stale-route');
54
+ const readPage = async params => {
55
+ const response = await checkedSdkRead(() => client.im.v1.message.list({ params }, { signal }), signal);
56
+ signal?.throwIfAborted();
57
+ const items = response?.data?.items;
58
+ if (!Array.isArray(items) || items.length > query.limit || typeof response.data.has_more !== 'boolean')
59
+ refuse('history-unavailable');
60
+ const events = [];
61
+ let omitted = 0;
62
+ for (const item of items) {
63
+ if (!item || item.chat_id !== route.conversationId
64
+ || (query.scope === 'thread' && item.thread_id !== route.threadId)) refuse('untrusted-source');
65
+ if (item.deleted || item.msg_type !== 'text' || item.sender?.sender_type !== 'user'
66
+ || item.sender?.id_type !== 'open_id') { ++omitted; continue; }
67
+ if (item.mentions !== undefined && (!Array.isArray(item.mentions) || item.mentions.length > 100)) { ++omitted; continue; }
68
+ let event;
69
+ try { event = normalizeExternalText({ event_id: `history:${item.message_id}`,
70
+ sender: { sender_type: 'user', sender_id: { open_id: item.sender.id }, sender_name: item.sender.sender_name },
71
+ message: { ...item, chat_type: 'group', message_type: item.msg_type, content: item.body?.content,
72
+ mentions: (item.mentions ?? []).map(mention => ({ ...mention, id: { open_id: mention?.id } })) },
73
+ }, identity); } catch (error) {
74
+ if (error?.code !== 'invalid-inbound') throw error;
75
+ ++omitted; continue;
76
+ }
77
+ if (!event) { ++omitted; continue; }
78
+ events.push(event);
79
+ }
80
+ const nextCursor = response.data.has_more ? response.data.page_token : undefined;
81
+ if (response.data.has_more && (typeof nextCursor !== 'string' || !nextCursor || nextCursor.length > 4096))
82
+ refuse('history-unavailable');
83
+ return {events, omitted, hasMore:response.data.has_more, ...(nextCursor ? {nextCursor} : {})};
84
+ };
85
+ if (query.scope === 'nearby') return readNearbyHistory(readPage, route, query, Number(source.create_time));
86
+ if (query.beforeCount !== undefined || query.afterCount !== undefined) refuse('bad-request');
87
+ const page = await readPage({container_id_type:query.scope === 'thread' ? 'thread' : 'chat',
88
+ container_id:query.scope === 'thread' ? route.threadId : route.conversationId,
89
+ sort_type:'ByCreateTimeDesc', page_size:query.limit, with_sender_name:true,
90
+ ...(query.cursor === undefined ? {} : {page_token:query.cursor})});
91
+ return {version:1, scope:query.scope, ...page, coverage:'provider-visible-human-text'};
92
+ }
@@ -1,3 +1,4 @@
1
+ import { ExclusiveInboundConsumers, normalizeExternalText } from './external-consumer.mjs';
1
2
  import { atConnectionStage, createConnectionDiagnostics } from '../shared/connection-error.mjs';
2
3
  import { createHash, randomUUID } from 'node:crypto';
3
4
  import { connectionTestMessage } from '../shared/connection-test.mjs';
@@ -93,6 +94,7 @@ function secretRefFor(botId) {
93
94
  function configuredBotFingerprint(config) {
94
95
  return JSON.stringify({
95
96
  id: config.id,
97
+ consumerMode: config.consumerMode ?? 'standalone',
96
98
  appId: config.appId,
97
99
  secretRef: config.secretRef,
98
100
  ownerOpenIds: config.ownerOpenIds,
@@ -113,6 +115,14 @@ function configuredBotFingerprint(config) {
113
115
  });
114
116
  }
115
117
 
118
+ // Account/ownership fences must not include settings that are hot-updated on
119
+ // the same runtime (step push, voice, slash panel or group presentation).
120
+ function externalAccountOwnership(config) {
121
+ return JSON.stringify({ id: config.id, consumerMode: config.consumerMode ?? 'standalone',
122
+ appId: config.appId, secretRef: config.secretRef, ownerOpenIds: config.ownerOpenIds,
123
+ domain: config.domain, botOpenId: config.botOpenId, deletionPending: config.deletionPending === true });
124
+ }
125
+
116
126
  function optionalNonEmptyString(value) {
117
127
  return typeof value === 'string' && value.trim() ? value.trim() : null;
118
128
  }
@@ -133,6 +143,7 @@ export class MultiBotDshFeishuController {
133
143
  #createBotId;
134
144
  #createRegistrationId;
135
145
  #runtimes = new Map();
146
+ #inboundConsumers = new ExclusiveInboundConsumers();
136
147
  #botErrors = new Map();
137
148
  #registrations = new Map();
138
149
  #activeAppUpdates = new Map();
@@ -594,7 +605,82 @@ export class MultiBotDshFeishuController {
594
605
  this.#assertOpen('capability-unavailable');
595
606
  return { version: 1, botId, channel: 'feishu', account,
596
607
  connected: isConnected(connectionStatus(this.#runtimes.get(botId))),
597
- capabilities: ['proactive-text-checked', 'proactive-receipt-checked'] };
608
+ capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'exclusive-text-consumer', 'reply-text-checked', 'history-text-checked', 'thread-history-text-checked'] };
609
+ });
610
+ }
611
+
612
+ async consumeInbound(botId, { expectedFingerprint, onEvent, signal } = {}) {
613
+ this.#assertOpen();
614
+ return this.#serializeConfig(() => this.#withBotTransition(botId, async () => {
615
+ this.#assertOpen();
616
+ signal?.throwIfAborted();
617
+ const config = this.#requireBot(botId);
618
+ const account = await this.#deliveryAccount(config);
619
+ this.#assertOpen('capability-unavailable');
620
+ signal?.throwIfAborted();
621
+ if (account.fingerprint !== expectedFingerprint)
622
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
623
+ const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal });
624
+ try {
625
+ const saved = await this.#configStore.saveBot({ ...config, consumerMode: 'external-consumer' });
626
+ this.#assertOpen('capability-unavailable');
627
+ signal?.throwIfAborted();
628
+ const resolved = await this.#credentials.resolve(saved.secretRef);
629
+ this.#assertOpen('capability-unavailable');
630
+ signal?.throwIfAborted();
631
+ if (!resolved?.value) throw Object.assign(new Error('account-unverified'), { code: 'account-unverified' });
632
+ await this.#startRuntime(saved, resolved.value);
633
+ signal?.throwIfAborted();
634
+ this.#touch();
635
+ return dispose;
636
+ } catch (error) {
637
+ dispose();
638
+ throw error;
639
+ }
640
+ }));
641
+ }
642
+
643
+ async historyChecked(botId, route, query, { expectedFingerprint, signal } = {}) {
644
+ this.#assertOpen('capability-unavailable');
645
+ return this.#withBotTransition(botId, async () => {
646
+ this.#assertOpen('capability-unavailable');
647
+ signal?.throwIfAborted();
648
+ const config = this.#requireBot(botId);
649
+ const account = await this.#deliveryAccount(config);
650
+ this.#assertOpen('capability-unavailable');
651
+ signal?.throwIfAborted();
652
+ if (account.fingerprint !== expectedFingerprint)
653
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
654
+ const runtime = this.#runtimes.get(botId);
655
+ if (config.consumerMode !== 'external-consumer' || !isConnected(connectionStatus(runtime))
656
+ || typeof runtime.historyChecked !== 'function')
657
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
658
+ const leaseSignal = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
659
+ const readSignal = signal ? AbortSignal.any([signal, leaseSignal]) : leaseSignal;
660
+ const result = await runtime.historyChecked({ botId, appId: config.appId,
661
+ botOpenId: config.botOpenId, fingerprint: account.fingerprint }, route, query, { signal: readSignal });
662
+ this.#assertOpen('capability-unavailable');
663
+ readSignal.throwIfAborted();
664
+ return result;
665
+ });
666
+ }
667
+
668
+ async replyChecked(botId, route, text, { expectedFingerprint, signal } = {}) {
669
+ this.#assertOpen();
670
+ return this.#withBotTransition(botId, async () => {
671
+ this.#assertOpen();
672
+ const config = this.#requireBot(botId);
673
+ const account = await this.#deliveryAccount(config);
674
+ this.#assertOpen('capability-unavailable');
675
+ signal?.throwIfAborted();
676
+ if (account.fingerprint !== expectedFingerprint)
677
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
678
+ signal?.throwIfAborted();
679
+ const runtime = this.#runtimes.get(botId);
680
+ if (config.consumerMode !== 'external-consumer' || !isConnected(connectionStatus(runtime))
681
+ || typeof runtime.replyChecked !== 'function')
682
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
683
+ return runtime.replyChecked(route, text, { signal });
598
684
  });
599
685
  }
600
686
 
@@ -628,6 +714,18 @@ export class MultiBotDshFeishuController {
628
714
  });
629
715
  }
630
716
 
717
+ async presentSessionSyncApproval(botId, target, interaction, options = {}) {
718
+ this.#assertOpen();
719
+ return this.#withBotTransition(botId, async () => {
720
+ this.#assertOpen();
721
+ this.#requireBot(botId);
722
+ const runtime = this.#runtimes.get(botId);
723
+ if (!isConnected(connectionStatus(runtime))
724
+ || typeof runtime.presentSessionSyncApproval !== 'function') return false;
725
+ return runtime.presentSessionSyncApproval(target, interaction, options);
726
+ });
727
+ }
728
+
631
729
  async disconnectBot(botId) {
632
730
  this.#assertOpen();
633
731
  // An operational pause only: credentials/config remain durable, so the
@@ -761,6 +859,7 @@ export class MultiBotDshFeishuController {
761
859
  async close() {
762
860
  if (this.#closed) return;
763
861
  this.#closed = true;
862
+ this.#inboundConsumers.close();
764
863
  const appUpdateProcessing = [];
765
864
  for (const record of this.#registrations.values()) {
766
865
  const state = record.manager.status().state;
@@ -1352,11 +1451,39 @@ export class MultiBotDshFeishuController {
1352
1451
 
1353
1452
  async #startRuntime(config, appSecret) {
1354
1453
  await this.#stopRuntime(config.id);
1355
- const runtime = await atConnectionStage('runtime.prepare', () => this.#createRuntime({
1454
+ let runtime;
1455
+ runtime = await atConnectionStage('runtime.prepare', () => this.#createRuntime({
1356
1456
  botId: config.id,
1357
1457
  config,
1358
1458
  appSecret,
1359
1459
  repair: this.#runtimeRepairCapability(config.id),
1460
+ acceptExternal: async (event, { signal } = {}) => {
1461
+ const assertCurrent = () => {
1462
+ this.#assertOpen('capability-unavailable');
1463
+ signal?.throwIfAborted();
1464
+ if (this.#runtimes.get(config.id) !== runtime)
1465
+ throw Object.assign(new Error('consumer-unavailable'), { code: 'consumer-unavailable' });
1466
+ const current = this.#requireBot(config.id);
1467
+ if (current.consumerMode !== 'external-consumer'
1468
+ || externalAccountOwnership(current) !== externalAccountOwnership(config))
1469
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
1470
+ return current;
1471
+ };
1472
+ const evidence = await this.#withBotTransition(config.id, async () => {
1473
+ const current = assertCurrent();
1474
+ const account = await this.#deliveryAccount(current);
1475
+ assertCurrent();
1476
+ return normalizeExternalText(event, { botId: current.id, appId: current.appId,
1477
+ botOpenId: current.botOpenId, fingerprint: account.fingerprint });
1478
+ });
1479
+ // Never hold the account queue across application work: onEvent may
1480
+ // await a checked read/reply, and stop must be able to abort its signal.
1481
+ assertCurrent();
1482
+ if (evidence === null) return { accepted: true, ignored: true };
1483
+ const result = await this.#inboundConsumers.accept(config.id, evidence, signal);
1484
+ assertCurrent();
1485
+ return result;
1486
+ },
1360
1487
  }));
1361
1488
  this.#runtimes.set(config.id, runtime);
1362
1489
  try {
@@ -1398,6 +1525,7 @@ export class MultiBotDshFeishuController {
1398
1525
  async #deleteBot(botId) {
1399
1526
  let config = this.#configStore.getBot(botId);
1400
1527
  if (!config) return;
1528
+ this.#inboundConsumers.remove(botId);
1401
1529
  if (!config.deletionPending) {
1402
1530
  config = await this.#configStore.saveBot({ ...config, deletionPending: true });
1403
1531
  }
@@ -0,0 +1,72 @@
1
+ function refuse(code) { throw Object.assign(new Error(code), { code }); }
2
+ const count = value => Number.isInteger(value) && value >= 0 && value <= 20;
3
+
4
+ export async function readNearbyHistory(readPage, route, query, anchorTime) {
5
+ const before = query.beforeCount ?? 10;
6
+ const after = query.afterCount ?? 5;
7
+ if (!count(before) || !count(after)) refuse('bad-request');
8
+ const start = Math.max(0, anchorTime - 300000);
9
+ const end = anchorTime + 300000;
10
+ const window = { start: Math.floor(start / 1000), end: Math.floor(end / 1000) + 1 };
11
+ let state = { phase: 'window', before: 0, after: 0 };
12
+ if (query.cursor !== undefined) {
13
+ try {
14
+ const decoded = JSON.parse(Buffer.from(query.cursor, 'base64url').toString());
15
+ if (decoded.version !== 1 || decoded.anchor !== route.messageId || decoded.at !== anchorTime
16
+ || decoded.minBefore !== before || decoded.minAfter !== after || decoded.limit !== query.limit
17
+ || !['window', 'before', 'after'].includes(decoded.phase)
18
+ || !count(decoded.before) || !count(decoded.after)
19
+ || (decoded.page !== undefined && (typeof decoded.page !== 'string' || !decoded.page || decoded.page.length > 3000)))
20
+ refuse('bad-request');
21
+ state = decoded;
22
+ } catch { refuse('bad-request'); }
23
+ }
24
+ const params = { container_id_type: 'chat', container_id: route.conversationId,
25
+ page_size: query.limit, with_sender_name: true,
26
+ sort_type: state.phase === 'before' ? 'ByCreateTimeDesc' : 'ByCreateTimeAsc',
27
+ ...(state.page === undefined ? {} : { page_token: state.page }),
28
+ ...(state.phase === 'window' ? { start_time: String(window.start), end_time: String(window.end) }
29
+ : state.phase === 'before' ? { end_time: String(window.start + 1) }
30
+ : { start_time: String(Math.floor(end / 1000)) }),
31
+ };
32
+ // Lark defaults an omitted end_time to now and rejects a future start_time.
33
+ // A fresh anchor has no existing messages beyond its future window boundary.
34
+ const page = state.phase === 'after' && end >= Date.now()
35
+ ? { events: [], omitted: 0, hasMore: false }
36
+ : await readPage(params);
37
+ const events = [];
38
+ for (const event of page.events) {
39
+ const at = Date.parse(event.at);
40
+ if (!Number.isFinite(at)) refuse('history-unavailable');
41
+ if (state.phase === 'window') {
42
+ if (at < start || at > end) continue;
43
+ events.push(event);
44
+ if (event.messageId !== route.messageId && at < anchorTime) state.before = Math.min(20, state.before + 1);
45
+ if (event.messageId !== route.messageId && at > anchorTime) state.after = Math.min(20, state.after + 1);
46
+ } else if (state.phase === 'before' && at < start && state.before < before) {
47
+ events.push(event); state.before++;
48
+ } else if (state.phase === 'after' && at > end && state.after < after) {
49
+ events.push(event); state.after++;
50
+ }
51
+ }
52
+ const needsPage = page.hasMore && (state.phase === 'window'
53
+ || (state.phase === 'before' ? state.before < before : state.after < after));
54
+ if (needsPage) {
55
+ if (page.nextCursor === state.page) refuse('history-unavailable');
56
+ state.page = page.nextCursor;
57
+ } else {
58
+ delete state.page;
59
+ if (state.phase === 'window' && state.before < before) state.phase = 'before';
60
+ else if (state.phase !== 'after' && state.after < after) state.phase = 'after';
61
+ else state.phase = 'done';
62
+ }
63
+ let nextCursor;
64
+ if (state.phase !== 'done') {
65
+ nextCursor = Buffer.from(JSON.stringify({version:1, anchor:route.messageId, at:anchorTime,
66
+ minBefore:before, minAfter:after, limit:query.limit, phase:state.phase,
67
+ before:state.before, after:state.after, ...(state.page ? {page:state.page} : {})})).toString('base64url');
68
+ if (nextCursor.length > 4096) refuse('history-unavailable');
69
+ }
70
+ return {version:1, scope:'nearby', events, omitted:page.omitted, hasMore:!!nextCursor,
71
+ ...(nextCursor ? {nextCursor} : {}), window, coverage:'provider-visible-human-text'};
72
+ }
@@ -40,6 +40,7 @@ function normalizeBot(value, { legacy = false } = {}) {
40
40
  const domain = value.domain === 'lark' ? 'lark' : 'feishu';
41
41
  return Object.freeze({
42
42
  id,
43
+ consumerMode: value.consumerMode === 'external-consumer' ? 'external-consumer' : 'standalone',
43
44
  appId,
44
45
  secretRef,
45
46
  ownerOpenIds: Object.freeze(ownerOpenIds),
@@ -224,6 +224,15 @@ export class MatrixController {
224
224
  return { sent: true };
225
225
  }
226
226
 
227
+ async presentSessionSyncApproval(botId, target, interaction, options = {}) {
228
+ this.#requireId(botId);
229
+ const runtime = this.#runtimes.get(botId);
230
+ if (!runtime?.status?.ready || typeof runtime.presentSessionSyncApproval !== 'function') {
231
+ throw new Error('Matrix bot is not connected for proactive delivery');
232
+ }
233
+ return runtime.presentSessionSyncApproval(target, interaction, options);
234
+ }
235
+
227
236
  async deleteBot(botId) {
228
237
  this.#requireId(botId);
229
238
  const removed = await this.#withBotTransition(botId, async () => {
@@ -173,6 +173,7 @@ export class MatrixRuntime {
173
173
  #replyTimeoutMs;
174
174
  #api = null;
175
175
  #bridge = null;
176
+ #approvalController = new AbortController();
176
177
  #botUserId = null;
177
178
  #deviceId = null;
178
179
  #crypto = null;
@@ -289,6 +290,7 @@ export class MatrixRuntime {
289
290
  async start() {
290
291
  if (this.#started && this.#status.ready) return;
291
292
  this.#stopped = false;
293
+ this.#approvalController = new AbortController();
292
294
  this.#started = true;
293
295
  const generation = ++this.#generation;
294
296
  const homeserver = this.#config.homeserver;
@@ -361,6 +363,7 @@ export class MatrixRuntime {
361
363
  async stop() {
362
364
  if (this.#stopped) return;
363
365
  this.#stopped = true;
366
+ this.#approvalController.abort();
364
367
  this.#started = false;
365
368
  this.#generation += 1;
366
369
  if (this.#reconnectTimer !== null) clearTimeout(this.#reconnectTimer);
@@ -389,6 +392,17 @@ export class MatrixRuntime {
389
392
  return await bridge.sendConnectionTest(text);
390
393
  }
391
394
 
395
+ async presentSessionSyncApproval(target, interaction, options = {}) {
396
+ if (!this.#status.ready || !this.#bridge) return false;
397
+ const actor = typeof target?.route?.userId === 'string' ? target.route.userId.trim() : '';
398
+ if (!actor) return false;
399
+ return this.#bridge.presentSessionSyncApproval(interaction, {
400
+ key: options.key.startsWith('dm:') ? `direct:${options.key}` : options.key,
401
+ actor, validate: options.validate,
402
+ send: (text) => this.sendProactiveText(target, text),
403
+ }, { ...options, runtimeSignal: this.#approvalController.signal });
404
+ }
405
+
392
406
  async sendProactiveText(target, text, options = {}) {
393
407
  const api = this.#api;
394
408
  if (!api) throw new Error('Matrix bot is not connected');
@@ -1337,6 +1337,12 @@ export class QqHarnessBridge {
1337
1337
  }
1338
1338
  }
1339
1339
 
1340
+ async presentSessionSyncApproval(interaction, context, options = {}) {
1341
+ return this.#approvals.handleSessionSyncRequested(interaction, context, {
1342
+ ...options, runtimeSignal: this.#signal, accessPolicy: this.#accessPolicy,
1343
+ });
1344
+ }
1345
+
1340
1346
  async #handleInteraction(interaction, {
1341
1347
  key,
1342
1348
  actor,
@@ -297,6 +297,20 @@ export class QqController {
297
297
  });
298
298
  }
299
299
 
300
+ async presentSessionSyncApproval(botId, target, interaction, options = {}) {
301
+ const config = this.#configStore.get(botId);
302
+ if (!config) throw new Error('Unknown QQ bot');
303
+ return this.#withBotTransition(botId, async () => {
304
+ const runtime = this.#runtimes.get(botId);
305
+ if (!runtime?.status?.ready || typeof runtime.presentSessionSyncApproval !== 'function') {
306
+ const error = new Error(t('QQ机器人尚未连接'));
307
+ error.code = 'bot-not-connected';
308
+ throw error;
309
+ }
310
+ return runtime.presentSessionSyncApproval(target, interaction, options);
311
+ });
312
+ }
313
+
300
314
  async deleteBot(botId) {
301
315
  const warnings = [];
302
316
  const config = this.#configStore.get(botId);
@@ -104,6 +104,16 @@ export class QqRuntime {
104
104
  return { sent: true };
105
105
  }
106
106
 
107
+ async presentSessionSyncApproval(target, interaction, options = {}) {
108
+ if (!this.#status.ready || !this.#bridge) return false;
109
+ const actor = typeof target?.route?.userOpenId === 'string' ? target.route.userOpenId.trim() : '';
110
+ if (!actor) return false;
111
+ return this.#bridge.presentSessionSyncApproval(interaction, {
112
+ key: options.key, actor, validate: options.validate,
113
+ send: (text) => this.sendProactiveText(target, text),
114
+ }, options);
115
+ }
116
+
107
117
  async sendProactiveText(target, text, { signal } = {}) {
108
118
  const nativeId = target?.kind === 'user'
109
119
  ? (typeof target?.route?.userOpenId === 'string' ? target.route.userOpenId.trim() : '')
@@ -62,6 +62,7 @@ export function extractConnectionEvidence(error) {
62
62
  ...(reasons.length > 1 ? { reasons } : {}),
63
63
  httpStatus: errors.find(e => e.httpStatus !== undefined)?.httpStatus,
64
64
  providerCode: errors.find(e => e.providerCode !== undefined)?.providerCode,
65
+ method: first('method'), transport: first('transport'),
65
66
  durationMs: first('durationMs'), timeoutMs: first('timeoutMs'), host: first('host'), truncated,
66
67
  }),
67
68
  };
@@ -20,6 +20,12 @@ const REASONS = new Set([
20
20
  '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',
21
21
  ]);
22
22
  const RESOURCES = new Set(['credential-store', 'account-config', 'account-state', 'workspace-config', 'workspace-directory']);
23
+ const RPC_METHODS = new Set([
24
+ 'host.describe', 'workspace.list', 'workspace.create', 'session.list', 'session.create',
25
+ 'session.history', 'session.prompt', 'session.rename', 'session.cancel', 'session.models',
26
+ 'session.permissions', 'session.selectModel', 'llm.models',
27
+ ]);
28
+ const TRANSPORTS = new Set(['host-api', 'http']);
23
29
  const CONFIG_FILES = new Set(['config.json', 'workspaces.json']);
24
30
  export const CONFIG_ISSUE_LABELS = Object.freeze({
25
31
  'expected-object': '应为 JSON 对象。',
@@ -44,7 +50,7 @@ const CONFIG_FIELD = /^(?:\$|version|accounts(?:\[\d{1,10}\](?:\.(?:accountId|ow
44
50
  export function normalizeDiagnosticDetails(value) {
45
51
  if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
46
52
  const result = {};
47
- for (const [field, allowed] of [['operation', OPERATIONS], ['stage', STAGES], ['reason', REASONS], ['resource', RESOURCES]]) {
53
+ for (const [field, allowed] of [['operation', OPERATIONS], ['stage', STAGES], ['reason', REASONS], ['resource', RESOURCES], ['method', RPC_METHODS], ['transport', TRANSPORTS]]) {
48
54
  if (allowed.has(value[field])) result[field] = value[field];
49
55
  }
50
56
  if (DIAGNOSTIC_CHANNELS.includes(value.channel)) result.channel = value.channel;