@botharness/im-provider 4.32.0-botharness.16 → 4.32.0-botharness.21

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 (45) hide show
  1. package/PROVENANCE.json +9 -9
  2. package/lib/client.js +8 -5
  3. package/lib/index.js +305 -308
  4. package/package.json +6 -5
  5. package/plugin-src/host/app-setup.mjs +244 -0
  6. package/plugin-src/host/build.mjs +3 -2
  7. package/plugin-src/host/channels/qq/production.mjs +7 -1
  8. package/plugin-src/host/channels/shared/startup.mjs +3 -0
  9. package/plugin-src/host/delivery-adapter.mjs +15 -0
  10. package/plugin-src/host/delivery-service.mjs +103 -3
  11. package/plugin-src/host/index.mjs +15 -2
  12. package/plugin-src/host/qq-sdk-observation-patch.mjs +53 -0
  13. package/src/channels/discord/discord-api.mjs +9 -0
  14. package/src/channels/discord/discord-controller.mjs +1 -2
  15. package/src/channels/discord/discord-runtime.mjs +13 -0
  16. package/src/channels/discord/reachable-conversations.mjs +211 -0
  17. package/src/channels/feishu/external-cards.mjs +63 -6
  18. package/src/channels/feishu/external-reactions.mjs +36 -0
  19. package/src/channels/feishu/feishu-runtime.mjs +95 -2
  20. package/src/channels/feishu/multi-bot-controller.mjs +78 -4
  21. package/src/channels/qq/config-store.mjs +1 -0
  22. package/src/channels/qq/external-addressing.mjs +6 -0
  23. package/src/channels/qq/external-consumer.mjs +214 -0
  24. package/src/channels/qq/external-files.mjs +50 -0
  25. package/src/channels/qq/external-images.mjs +109 -0
  26. package/src/channels/qq/external-mentions.mjs +32 -0
  27. package/src/channels/qq/external-post.mjs +51 -0
  28. package/src/channels/qq/external-voice.mjs +32 -0
  29. package/src/channels/qq/native-gateway-diagnostics.mjs +86 -0
  30. package/src/channels/qq/native-reply-observations.mjs +143 -0
  31. package/src/channels/qq/native-transport-diagnostics.mjs +42 -0
  32. package/src/channels/qq/qq-controller.mjs +105 -1
  33. package/src/channels/qq/qq-runtime.mjs +259 -12
  34. package/src/channels/qq/sdk-frame-observation.mjs +31 -0
  35. package/src/channels/qq/voice-attachment.mjs +3 -0
  36. package/src/channels/shared/i18n-en/qq.mjs +4 -0
  37. package/src/channels/shared/i18n-en/weixin.mjs +1 -0
  38. package/src/channels/shared/token-bot-controller.mjs +26 -0
  39. package/src/channels/slack/reachable-conversations.mjs +136 -0
  40. package/src/channels/slack/slack-api.mjs +9 -1
  41. package/src/channels/slack/slack-controller.mjs +25 -2
  42. package/src/channels/slack/slack-runtime.mjs +23 -0
  43. package/src/channels/weixin/connection-error.en.mjs +1 -0
  44. package/src/channels/weixin/connection-error.mjs +1 -0
  45. package/src/channels/weixin/weixin-controller.mjs +23 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botharness/im-provider",
3
- "version": "4.32.0-botharness.16",
3
+ "version": "4.32.0-botharness.21",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "BotHarness-qualified IM Provider, maintained from dsh-im",
6
6
  "keywords": [
@@ -148,7 +148,7 @@
148
148
  "platform": "web"
149
149
  },
150
150
  "compatibility": {
151
- "dsh": ">=0.1.7-0",
151
+ "dsh": ">=0.2.0-0",
152
152
  "profiles": [
153
153
  "web"
154
154
  ]
@@ -156,7 +156,7 @@
156
156
  },
157
157
  "engines": {
158
158
  "node": ">=22",
159
- "dsh": ">=0.1.7-0"
159
+ "dsh": ">=0.2.0-0"
160
160
  },
161
161
  "dependencies": {
162
162
  "@matrix-org/olm": "3.2.15",
@@ -168,7 +168,8 @@
168
168
  "mailparser": "^3.9.28",
169
169
  "nodemailer": "^10.0.10",
170
170
  "qrcode": "1.5.4",
171
- "undici": "7.29.1"
171
+ "undici": "7.29.1",
172
+ "ws": "8.21.3"
172
173
  },
173
174
  "optionalDependencies": {
174
175
  "@tencent-qqmail/agently-cli": "^1.0.18",
@@ -177,6 +178,6 @@
177
178
  "peerDependencies": {},
178
179
  "botharness": {
179
180
  "managedByProduct": true,
180
- "upstreamSource": "36da305c9586335a47d4bab6ee4f0025247a9d8f"
181
+ "upstreamSource": "beaed4a6dabb583654d28fb09298716267039b4a"
181
182
  }
182
183
  }
@@ -0,0 +1,244 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import QRCode from 'qrcode';
3
+ import { registerManagementRpc } from '../management-rpc.mjs';
4
+
5
+ const ENDPOINT = 'dsh-im/app-setup';
6
+ const TTL = 10 * 60_000;
7
+ const failure = (code) => Object.assign(new Error(code), { code });
8
+
9
+ /** Provider-owned setup sessions. Credentials never cross the same-Host Service. */
10
+ export class AppSetupService {
11
+ #channels = new Map();
12
+ #attempts = new Map();
13
+ #describeBot;
14
+ #logger;
15
+
16
+ constructor({ describeBot, logger }) {
17
+ this.#describeBot = describeBot;
18
+ this.#logger = logger;
19
+ }
20
+
21
+ #record(phase, channel, startedAt, reason) {
22
+ try {
23
+ this.#logger?.info?.(JSON.stringify({ event: 'im-app-setup', initiator: 'client',
24
+ ...(['feishu', 'weixin'].includes(channel) ? { channel } : {}), phase,
25
+ durationMs: Math.max(0, Date.now() - startedAt), ...(reason ? { reason } : {}) }));
26
+ } catch {}
27
+ }
28
+
29
+ register(channel, controller) {
30
+ if (!['feishu', 'weixin'].includes(channel)) return () => {};
31
+ const previous = this.#channels.get(channel);
32
+ if (previous) this.#retire(channel, previous);
33
+ const registration = { controller };
34
+ this.#channels.set(channel, registration);
35
+ return () => this.#retire(channel, registration);
36
+ }
37
+
38
+ #retire(channel, registration) {
39
+ if (this.#channels.get(channel) === registration) this.#channels.delete(channel);
40
+ for (const attempt of this.#attempts.values()) {
41
+ if (attempt.registration !== registration || attempt.controller.signal.aborted) continue;
42
+ attempt.controller.abort();
43
+ void this.#stopQr(attempt).catch(() => undefined);
44
+ this.#record('disposed', channel, attempt.startedAt);
45
+ }
46
+ }
47
+
48
+ describe(channel) {
49
+ return this.#channels.has(channel)
50
+ ? { version: 1, channel, endpoint: ENDPOINT, kind: channel === 'weixin' ? 'qr' : 'credentials' }
51
+ : undefined;
52
+ }
53
+
54
+ async call(method, payload, signal) {
55
+ const startedAt = Date.now();
56
+ try { return await this.#call(method, payload, signal); }
57
+ catch (error) {
58
+ const reason = ['bad-request', 'capability-unavailable', 'setup-expired', 'setup-limit', 'setup-account-exists'].includes(error?.code)
59
+ ? error.code : signal?.aborted || this.#attempts.get(payload?.attemptId)?.controller.signal.aborted
60
+ ? 'cancelled' : 'setup-failed';
61
+ this.#record('refused', this.#attempts.get(payload?.attemptId)?.channel, startedAt, reason);
62
+ throw error;
63
+ }
64
+ }
65
+
66
+ async #call(method, payload, signal) {
67
+ signal?.throwIfAborted();
68
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw failure('bad-request');
69
+ if (method === 'setup.start') {
70
+ if (Object.keys(payload).some((key) => key !== 'channel')) throw failure('bad-request');
71
+ const registration = this.#channels.get(payload.channel);
72
+ if (!registration) throw failure('capability-unavailable');
73
+ for (const [id, attempt] of this.#attempts) {
74
+ if (attempt.expiresAt <= Date.now()) {
75
+ attempt.controller.abort();
76
+ await this.#stopQr(attempt);
77
+ this.#attempts.delete(id);
78
+ this.#record('expired', attempt.channel, attempt.startedAt);
79
+ }
80
+ }
81
+ if (this.#attempts.size >= 32) throw failure('setup-limit');
82
+ const attempt = { attemptId: randomUUID(), channel: payload.channel, registration, controller: new AbortController(),
83
+ state: 'credentials', startedAt: Date.now(), expiresAt: Date.now() + TTL };
84
+ this.#attempts.set(attempt.attemptId, attempt);
85
+ this.#record('started', attempt.channel, attempt.startedAt);
86
+ if (attempt.channel === 'weixin') {
87
+ attempt.state = 'creating';
88
+ this.#armExpiry(attempt);
89
+ attempt.operation = this.#beginQr(attempt);
90
+ try { return await attempt.operation; }
91
+ finally { delete attempt.operation; }
92
+ }
93
+ return this.#view(attempt);
94
+ }
95
+ const attempt = this.#attempts.get(payload.attemptId);
96
+ if (!attempt) throw failure('setup-expired');
97
+ if (attempt.expiresAt <= Date.now()) {
98
+ attempt.controller.abort();
99
+ await this.#stopQr(attempt);
100
+ this.#attempts.delete(attempt.attemptId);
101
+ this.#record('expired', attempt.channel, attempt.startedAt);
102
+ throw failure('setup-expired');
103
+ }
104
+ if (this.#channels.get(attempt.channel) !== attempt.registration) throw failure('capability-unavailable');
105
+ if (['setup.poll', 'setup.cancel'].includes(method)
106
+ && Object.keys(payload).some((key) => key !== 'attemptId')) throw failure('bad-request');
107
+ if (method === 'setup.poll') {
108
+ if (attempt.channel === 'weixin' && attempt.state !== 'ready') await this.#pollQr(attempt);
109
+ if (attempt.accountRef && !attempt.description) await this.#describe(attempt);
110
+ return this.#view(attempt);
111
+ }
112
+ if (method === 'setup.cancel') {
113
+ attempt.controller.abort();
114
+ await this.#stopQr(attempt);
115
+ await attempt.operation?.catch(() => undefined);
116
+ if (attempt.channel === 'weixin' && attempt.qrAttemptId) await this.#pollQr(attempt);
117
+ if (attempt.state !== 'ready') attempt.state = 'cancelled';
118
+ this.#record(attempt.state === 'ready' ? 'retained' : 'cancelled', attempt.channel, attempt.startedAt);
119
+ return this.#view(attempt);
120
+ }
121
+ if (method === 'setup.verify' && attempt.channel === 'weixin') {
122
+ if (attempt.state !== 'needs_verification'
123
+ || Object.keys(payload).some(key => !['attemptId', 'verifyCode'].includes(key))
124
+ || typeof payload.verifyCode !== 'string' || !/^\d{4,8}$/.test(payload.verifyCode)) throw failure('bad-request');
125
+ await attempt.registration.controller.submitVerification(attempt.qrAttemptId, payload.verifyCode);
126
+ await this.#pollQr(attempt);
127
+ return this.#view(attempt);
128
+ }
129
+ if (attempt.channel !== 'feishu' || method !== 'setup.credentials' || attempt.state !== 'credentials'
130
+ || Object.keys(payload).some((key) => !['attemptId', 'appId', 'appSecret', 'domain'].includes(key))
131
+ || typeof payload.appId !== 'string' || !/^cli_[A-Za-z0-9_-]+$/.test(payload.appId)
132
+ || typeof payload.appSecret !== 'string' || !payload.appSecret.trim() || payload.appSecret.length > 4096
133
+ || !['lark', 'feishu'].includes(payload.domain)) throw failure('bad-request');
134
+ attempt.state = 'creating';
135
+ this.#record('creating', attempt.channel, attempt.startedAt);
136
+ attempt.operation = this.#create(attempt, payload);
137
+ try { return await attempt.operation; }
138
+ finally { delete attempt.operation; }
139
+ }
140
+
141
+ async #beginQr(attempt) {
142
+ try {
143
+ const begun = await attempt.registration.controller.startProvisioning({
144
+ consumerMode: 'external-consumer', signal: attempt.controller.signal,
145
+ });
146
+ attempt.qrAttemptId = begun.attemptId;
147
+ attempt.expiresAt = Math.min(attempt.expiresAt, begun.expiresAt);
148
+ this.#armExpiry(attempt);
149
+ if (attempt.controller.signal.aborted) { await this.#stopQr(attempt); throw failure('setup-failed'); }
150
+ if (begun.verificationUrl) attempt.qrDataUrl = await QRCode.toDataURL(begun.verificationUrl, {
151
+ type: 'image/png', errorCorrectionLevel: 'M', margin: 2, width: 320,
152
+ });
153
+ attempt.controller.signal.throwIfAborted();
154
+ if (this.#channels.get(attempt.channel) !== attempt.registration) throw failure('capability-unavailable');
155
+ await this.#pollQr(attempt);
156
+ return this.#view(attempt);
157
+ } catch {
158
+ attempt.controller.abort();
159
+ await this.#stopQr(attempt);
160
+ if (attempt.state !== 'expired') attempt.state = 'failed';
161
+ throw failure('setup-failed');
162
+ }
163
+ }
164
+
165
+ async #stopQr(attempt) {
166
+ clearTimeout(attempt.expiryTimer);
167
+ if (attempt.qrAttemptId) await attempt.registration.controller.cancelProvisioning(attempt.qrAttemptId);
168
+ delete attempt.qrDataUrl;
169
+ }
170
+
171
+ #armExpiry(attempt) {
172
+ clearTimeout(attempt.expiryTimer);
173
+ attempt.expiryTimer = setTimeout(() => {
174
+ if (attempt.state === 'ready') return;
175
+ attempt.state = 'expired';
176
+ attempt.controller.abort();
177
+ void this.#stopQr(attempt).catch(() => undefined);
178
+ this.#record('expired', attempt.channel, attempt.startedAt);
179
+ }, Math.max(0, attempt.expiresAt - Date.now()));
180
+ attempt.expiryTimer.unref?.();
181
+ }
182
+
183
+ async #pollQr(attempt) {
184
+ const status = await attempt.registration.controller.registrationStatus(attempt.qrAttemptId);
185
+ if (!status) throw failure('setup-expired');
186
+ if (status.status === 'connected') {
187
+ if (!status.botId) throw failure('setup-failed');
188
+ attempt.accountRef = status.botId;
189
+ await this.#describe(attempt);
190
+ delete attempt.qrDataUrl;
191
+ } else if (['pending', 'scanned', 'needs_verification', 'connecting', 'expired', 'cancelled', 'failed'].includes(status.status)) {
192
+ attempt.state = status.status;
193
+ if (['expired', 'cancelled', 'failed'].includes(attempt.state)) delete attempt.qrDataUrl;
194
+ } else throw failure('setup-failed');
195
+ }
196
+
197
+ async #create(attempt, payload) {
198
+ try {
199
+ const created = await attempt.registration.controller.bindCredentials({
200
+ appId: payload.appId, appSecret: payload.appSecret, domain: payload.domain,
201
+ consumerMode: 'external-consumer',
202
+ signal: attempt.controller.signal,
203
+ });
204
+ if (!created.accountRef) throw failure('account-unverified');
205
+ attempt.accountRef = created.accountRef;
206
+ await this.#describe(attempt);
207
+ return this.#view(attempt);
208
+ } catch (error) {
209
+ attempt.state = attempt.controller.signal.aborted ? 'cancelled' : attempt.accountRef ? 'creating' : 'credentials';
210
+ throw failure(error?.code === 'setup-account-exists' ? error.code : 'setup-failed');
211
+ }
212
+ }
213
+
214
+ async #describe(attempt) {
215
+ if (this.#channels.get(attempt.channel) !== attempt.registration) throw failure('capability-unavailable');
216
+ const description = await this.#describeBot(attempt.accountRef);
217
+ if (this.#channels.get(attempt.channel) !== attempt.registration) throw failure('capability-unavailable');
218
+ attempt.description = { version: description.version, channel: description.channel,
219
+ botId: description.botId, account: { fingerprint: description.account.fingerprint,
220
+ ...(description.account.name ? { name: description.account.name } : {}) },
221
+ connected: description.connected, capabilities: [...description.capabilities] };
222
+ attempt.state = 'ready';
223
+ clearTimeout(attempt.expiryTimer);
224
+ this.#record('ready', attempt.channel, attempt.startedAt);
225
+ }
226
+
227
+ #view(attempt) {
228
+ return { version: 1, attemptId: attempt.attemptId, channel: attempt.channel,
229
+ state: attempt.state, expiresAt: attempt.expiresAt,
230
+ ...(attempt.qrDataUrl ? { qrDataUrl: attempt.qrDataUrl } : {}),
231
+ ...(attempt.accountRef ? { accountRef: attempt.accountRef, description: attempt.description } : {}) };
232
+ }
233
+ }
234
+
235
+ export function installAppSetupRpc(ctx, setup, authority) {
236
+ return registerManagementRpc(ctx, '/app-setup', async (method, payload, signal) => {
237
+ try { return { ok: true, value: await setup.call(method, payload, signal) }; }
238
+ catch (error) {
239
+ const code = ['bad-request', 'capability-unavailable', 'setup-expired', 'setup-limit', 'setup-account-exists'].includes(error?.code)
240
+ ? error.code : 'setup-failed';
241
+ return { ok: false, error: { code, message: code, details: {} } };
242
+ }
243
+ }, { authority });
244
+ }
@@ -5,13 +5,13 @@ import { fileURLToPath } from 'node:url';
5
5
  import { build } from 'esbuild';
6
6
 
7
7
  import { larkSdkHandshakePatch } from './lark-sdk-handshake-patch.mjs';
8
+ import { qqSdkObservationPatch } from './qq-sdk-observation-patch.mjs';
8
9
 
9
10
  const sourceDirectory = dirname(fileURLToPath(import.meta.url));
10
11
  const packageRoot = resolve(sourceDirectory, '../..');
11
12
  const outputPath = resolve(packageRoot, 'lib/index.js');
12
13
  const externalRuntimePackages = [
13
14
  '@tencent-connect/qqbot-connector',
14
- '@tencent-connect/qqbot-nodejs',
15
15
  '@wecom/aibot-node-sdk',
16
16
  'dingtalk-stream',
17
17
  'imapflow',
@@ -22,6 +22,7 @@ const externalRuntimePackages = [
22
22
  'undici',
23
23
  ];
24
24
  const external = externalRuntimePackages.flatMap((name) => [name, `${name}/*`]);
25
+ external.push('ws');
25
26
 
26
27
  await mkdir(dirname(outputPath), { recursive: true });
27
28
  await build({
@@ -32,7 +33,7 @@ await build({
32
33
  target: ['node22'],
33
34
  mainFields: ['module', 'main'],
34
35
  external,
35
- plugins: [larkSdkHandshakePatch],
36
+ plugins: [larkSdkHandshakePatch, qqSdkObservationPatch],
36
37
  outfile: outputPath,
37
38
  banner: {
38
39
  js: [
@@ -113,7 +113,7 @@ export async function createProductionController(ctx, config = {}, internals = {
113
113
  credentials: ctx.credentials,
114
114
  configStore: observedConfigStore,
115
115
  logger,
116
- createRuntime: async ({ botId, config: botConfig, appSecret }) => {
116
+ createRuntime: async ({ botId, config: botConfig, appSecret, externalConsumer, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText }) => {
117
117
  const state = await stateFor(botId);
118
118
  await workspaces.ensure(botId, {
119
119
  defaultAgentPreset: config.agentPreset,
@@ -125,6 +125,12 @@ export async function createProductionController(ctx, config = {}, internals = {
125
125
  return new Runtime({
126
126
  config: botConfig,
127
127
  appSecret,
128
+ externalConsumer,
129
+ sourceImages,
130
+ sourceFiles,
131
+ sourceVoiceTranscripts,
132
+ sourceVoiceAudio,
133
+ ordinaryText,
128
134
  harness: workspaceScope.harness,
129
135
  state: workspaceScope.state,
130
136
  contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
@@ -45,9 +45,11 @@ export async function installProductionChannel(ctx, config, {
45
45
  }, { authority: resolveRpcAuthority(config.rpcAuthority) });
46
46
  let production;
47
47
  let unregisterDelivery;
48
+ let unregisterSetup;
48
49
  let closing;
49
50
  const closeProduction = () => (closing ??= (async () => {
50
51
  try {
52
+ unregisterSetup?.();
51
53
  await unregisterDelivery?.();
52
54
  } finally {
53
55
  await production?.close();
@@ -61,6 +63,7 @@ export async function installProductionChannel(ctx, config, {
61
63
  ctx.effect(() => closeProduction, `dsh-im: close ${channel} connections`);
62
64
  followHostLanguage(ctx, channel, production.controller, logger);
63
65
  handler = readyHandler;
66
+ unregisterSetup = config.deliveryService?.appSetup?.register(channel, production.controller);
64
67
  } catch (error) {
65
68
  startupError = reportStartupError
66
69
  ? reportStartupError(error, false)
@@ -245,6 +245,11 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
245
245
  throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
246
246
  return coreController.consumeInbound(botId, options);
247
247
  },
248
+ reactionChecked: (botId, route, reaction, options) => {
249
+ if (channel !== 'feishu' || typeof coreController.reactionChecked !== 'function')
250
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
251
+ return coreController.reactionChecked(botId, route, reaction, options);
252
+ },
248
253
  approvalCardChecked: (botId, route, card, options) => {
249
254
  if (channel !== 'feishu' || typeof coreController.approvalCardChecked !== 'function')
250
255
  throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
@@ -284,6 +289,16 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
284
289
  return coreController.describeDeliveryAccount(botId);
285
290
  },
286
291
  ownsBot: (botId) => workspaces.has(botId),
292
+ listReachableConversations: (botId, options) => {
293
+ if (typeof coreController.listReachableConversations !== 'function')
294
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
295
+ return coreController.listReachableConversations(botId, options);
296
+ },
297
+ postConversationChecked: (botId, conversationId, text, options) => {
298
+ if (typeof coreController.postConversationChecked !== 'function')
299
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
300
+ return coreController.postConversationChecked(botId, conversationId, text, options);
301
+ },
287
302
  listBots: () => workspaces.listBotIds(),
288
303
  async listTargets(botId) {
289
304
  let targets = [...workspaces.listDeliveryTargets(botId)];
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { normalizeDeliveryTarget } from './delivery-adapter.mjs';
3
+ import { AppSetupService } from './app-setup.mjs';
3
4
 
4
5
  const BOT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
5
6
  const TARGET_ID_PATTERN = /^[A-Za-z0-9._:@-]{1,128}$/;
@@ -41,6 +42,9 @@ const DELIVERY_ERROR_CODES = new Set([
41
42
  'source-not-found',
42
43
  'source-unavailable',
43
44
  'reply-permission-denied',
45
+ 'reply-window-expired',
46
+ 'reply-limit-exceeded',
47
+ 'reply-rate-limited',
44
48
  'history-permission-denied',
45
49
  'history-unavailable',
46
50
  'thread-unavailable',
@@ -54,9 +58,14 @@ const DELIVERY_ERROR_CODES = new Set([
54
58
  'private-context-unavailable',
55
59
  'private-context-rejected',
56
60
  'send-permission-denied',
61
+ 'send-preflight-unavailable',
62
+ 'send-rate-limited',
57
63
  'typing-unavailable',
58
64
  'typing-conflict',
59
65
  'card-provider-rejected',
66
+ 'reaction-permission-denied',
67
+ 'reaction-provider-rejected',
68
+ 'reaction-result-unknown',
60
69
  ]);
61
70
 
62
71
  const SESSION_SYNC_METHODS = Object.freeze([
@@ -141,10 +150,12 @@ function sessionSyncState(value, available) {
141
150
  }
142
151
 
143
152
  export class DeliveryService {
153
+ appSetup;
144
154
  #adapters = new Map();
145
155
  #unavailableSessionSyncChannels;
146
156
 
147
- constructor({ unavailableSessionSyncChannels = [] } = {}) {
157
+ constructor({ unavailableSessionSyncChannels = [], logger } = {}) {
158
+ this.appSetup = new AppSetupService({ describeBot: (id) => this.describeBot(id), logger });
148
159
  if (!Array.isArray(unavailableSessionSyncChannels)
149
160
  || unavailableSessionSyncChannels.some((channel) => (
150
161
  typeof channel !== 'string' || !CHANNEL_PATTERN.test(channel)
@@ -341,6 +352,69 @@ export class DeliveryService {
341
352
  } catch (error) { throw publicOperationError(error); }
342
353
  }
343
354
 
355
+ async #reachableRegistration(botId, options) {
356
+ const id = botIdOf(botId);
357
+ cancellation(options.signal);
358
+ if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '')) throw deliveryError('bad-request');
359
+ const registration = await this.#checkedRegistrationFor(id);
360
+ const { adapter } = registration;
361
+ if (typeof adapter.describeAccount !== 'function' || typeof adapter.listReachableConversations !== 'function'
362
+ || typeof adapter.postConversationChecked !== 'function') throw deliveryError('capability-unavailable');
363
+ const account = await adapter.describeAccount(id);
364
+ this.#assertRegistered(registration);
365
+ cancellation(options.signal);
366
+ if (account?.version !== 1 || !account.capabilities?.includes('reachable-conversations-checked'))
367
+ throw deliveryError('capability-unavailable');
368
+ if (account.account?.fingerprint !== options.expectedFingerprint) throw deliveryError('account-changed');
369
+ if (account.connected !== true) throw deliveryError('bot-not-connected');
370
+ return { id, registration, signal: options.signal
371
+ ? AbortSignal.any([options.signal, registration.controller.signal]) : registration.controller.signal };
372
+ }
373
+
374
+ async listReachableConversations(botId, options = {}) {
375
+ try {
376
+ const { id, registration, signal } = await this.#reachableRegistration(botId, options);
377
+ const page = await registration.adapter.listReachableConversations(id, { ...options, signal });
378
+ this.#assertRegistered(registration);
379
+ cancellation(signal);
380
+ if (page?.version !== 1 || !Array.isArray(page.conversations) || page.conversations.length > 100
381
+ || typeof page.hasMore !== 'boolean' || (page.hasMore && (typeof page.cursor !== 'string' || !page.cursor || page.cursor.length > 2048)))
382
+ throw deliveryError('provider-unavailable');
383
+ const conversations = page.conversations.map(value => {
384
+ if (typeof value?.id !== 'string' || !value.id || value.id.length > 512 || value.kind !== 'group'
385
+ || typeof value.name !== 'string' || value.name.length > 512) throw deliveryError('provider-unavailable');
386
+ return { id: value.id, kind: value.kind, name: value.name };
387
+ });
388
+ return { version: 1, conversations, hasMore: page.hasMore, ...(page.hasMore ? { cursor: page.cursor } : {}) };
389
+ } catch (error) { throw publicOperationError(error, 'provider-unavailable'); }
390
+ }
391
+
392
+ async postConversationChecked(botId, conversationId, text, options = {}) {
393
+ if (typeof conversationId !== 'string' || !conversationId || conversationId.length > 512
394
+ || typeof text !== 'string' || !text.trim() || typeof options.beforeSend !== 'function')
395
+ throw deliveryError('bad-request');
396
+ let failureCode = 'send-preflight-unavailable';
397
+ try {
398
+ const { id, registration, signal } = await this.#reachableRegistration(botId, options);
399
+ const fence = () => {
400
+ this.#assertRegistered(registration);
401
+ cancellation(signal);
402
+ const allowed = options.beforeSend() === true;
403
+ this.#assertRegistered(registration);
404
+ cancellation(signal);
405
+ return allowed;
406
+ };
407
+ if (!fence()) throw deliveryError('send-permission-denied');
408
+ failureCode = 'send-result-unknown';
409
+ const result = await registration.adapter.postConversationChecked(id, conversationId, text,
410
+ { ...options, signal, beforeSend: fence });
411
+ if (result?.sent !== true || result.receipt?.version !== 1 || result.receipt.conversationId !== conversationId
412
+ || typeof result.receipt.messageId !== 'string' || !result.receipt.messageId || result.receipt.messageId.length > 512)
413
+ throw deliveryError('send-result-unknown');
414
+ return { sent: true, receipt: { version: 1, messageId: result.receipt.messageId, conversationId } };
415
+ } catch (error) { throw publicOperationError(error, failureCode); }
416
+ }
417
+
344
418
  async consumeInbound(botId, options = {}) {
345
419
  const id = botIdOf(botId);
346
420
  cancellation(options.signal);
@@ -376,6 +450,25 @@ export class DeliveryService {
376
450
  return dispose;
377
451
  }
378
452
 
453
+ async reactionChecked(botId, route, reaction, options = {}) {
454
+ const id = botIdOf(botId);
455
+ cancellation(options.signal);
456
+ if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '') ||
457
+ !['received', 'answered'].includes(reaction) || typeof options.beforeSend !== 'function')
458
+ throw deliveryError('bad-request');
459
+ const registration = await this.#checkedRegistrationFor(id);
460
+ if (registration.adapter.channel !== 'feishu' || typeof registration.adapter.reactionChecked !== 'function')
461
+ throw deliveryError('capability-unavailable');
462
+ this.#assertRegistered(registration);
463
+ try {
464
+ return await registration.adapter.reactionChecked(id, structuredClone(route), reaction, {
465
+ ...options, signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal])
466
+ : registration.controller.signal,
467
+ beforeSend: () => { this.#assertRegistered(registration); return options.beforeSend(); },
468
+ });
469
+ } catch (error) { throw publicOperationError(error, 'reaction-result-unknown'); }
470
+ }
471
+
379
472
  async approvalCardChecked(botId, route, card, options = {}) {
380
473
  const id = botIdOf(botId);
381
474
  cancellation(options.signal);
@@ -508,20 +601,27 @@ export class DeliveryService {
508
601
  if (account.account?.fingerprint !== expectedFingerprint) throw deliveryError('account-changed');
509
602
  const receiptConversation = adapter.channel === 'feishu' && target.kind === 'group'
510
603
  ? target.route.chatId : adapter.channel === 'slack' && target.kind === 'conversation'
511
- ? target.route.channelId : adapter.channel === 'weixin' && target.kind === 'user'
604
+ ? target.route.channelId : adapter.channel === 'qq' && target.kind === 'group'
605
+ ? target.route.groupOpenId : adapter.channel === 'weixin' && target.kind === 'user'
512
606
  ? target.route.toUserId : undefined;
513
607
  if (receipt && (!account.capabilities?.includes('proactive-receipt-checked') || !receiptConversation))
514
608
  throw deliveryError('capability-unavailable');
515
609
  if (receipt && adapter.channel === 'weixin' &&
516
610
  (!account.capabilities?.includes('proactive-fence-checked') || typeof beforeSend !== 'function'))
517
611
  throw deliveryError('capability-unavailable');
612
+ if (adapter.channel === 'qq' &&
613
+ (!account.capabilities?.includes('proactive-fence-checked') || typeof beforeSend !== 'function'))
614
+ throw deliveryError('capability-unavailable');
518
615
  cancellation(signal);
519
616
  this.#assertRegistered(registration);
520
617
  const deliverySignal = signal ? AbortSignal.any([signal, registration.controller.signal]) : registration.controller.signal;
521
618
  const fence = () => {
619
+ this.#assertRegistered(registration);
522
620
  cancellation(deliverySignal);
621
+ const allowed = beforeSend === undefined || (typeof beforeSend === 'function' && beforeSend() === true);
523
622
  this.#assertRegistered(registration);
524
- return beforeSend === undefined || beforeSend() === true;
623
+ cancellation(deliverySignal);
624
+ return allowed;
525
625
  };
526
626
  if (!fence()) throw deliveryError('send-permission-denied');
527
627
  const result = await adapter.sendText(id, target, text, { signal: deliverySignal, expectedFingerprint,
@@ -18,6 +18,7 @@ import { installHostLanguageRpc } from './host-language-rpc.mjs';
18
18
  import { installDeliveryRpc } from './delivery-rpc.mjs';
19
19
  import { installDeliveryHttp } from './delivery-http.mjs';
20
20
  import { createDeliveryService } from './delivery-service.mjs';
21
+ import { installAppSetupRpc } from './app-setup.mjs';
21
22
  import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
22
23
  import { installInjectedContext } from './injected-context.mjs';
23
24
  import { installSessionSyncCoordinator } from './session-sync-coordinator.mjs';
@@ -46,6 +47,7 @@ export function createImHostPlugin(internals = {}) {
46
47
  const startInboundTtl = internals.installInboundTtlRpc ?? installInboundTtlRpc;
47
48
  const startInjectedContext = internals.installInjectedContext ?? installInjectedContext;
48
49
  const startDelivery = internals.installDeliveryRpc ?? installDeliveryRpc;
50
+ const startAppSetup = internals.installAppSetupRpc ?? installAppSetupRpc;
49
51
  const startDeliveryHttp = internals.installDeliveryHttp ?? installDeliveryHttp;
50
52
  const startSessionSync = internals.installSessionSyncCoordinator
51
53
  ?? installSessionSyncCoordinator;
@@ -88,16 +90,26 @@ export function createImHostPlugin(internals = {}) {
88
90
  .map(([channel]) => channel)
89
91
  .filter((channel) => channel !== 'office'
90
92
  && config[channel]?.harnessBaseUrl !== undefined);
91
- const deliveryService = makeDeliveryService({ unavailableSessionSyncChannels });
93
+ const setupLogger = typeof ctx?.logger === 'function'
94
+ ? ctx.logger('dsh-im:app-setup') : (ctx?.logger ?? console);
95
+ const deliveryService = makeDeliveryService({ unavailableSessionSyncChannels, logger: setupLogger });
92
96
  if (typeof ctx?.provide === 'function') {
93
97
  ctx.provide('dshIm', Object.freeze({
94
98
  contractVersion: 1,
99
+ setupVersion: 1,
100
+ describeSetup: (channel) => deliveryService.appSetup.describe(channel),
101
+ reactionVersion: 1,
102
+ reactionChecked: (botId, route, reaction, options) => deliveryService.reactionChecked(botId, route, reaction, options),
95
103
  inboundVersion: 1,
96
104
  fileVersion: 1,
97
105
  approvalCardVersion: 1,
106
+ approvalRuleCardVersion: 2,
107
+ pairingCardVersion: 1,
98
108
  approvalCardChecked: (botId, route, card, options) => deliveryService.approvalCardChecked(botId, route, card, options),
99
109
  receiptVersion: 1,
100
- postFenceVersion: 1,
110
+ reachableConversationVersion: 1,
111
+ listReachableConversations: (botId, options) => deliveryService.listReachableConversations(botId, options),
112
+ postConversationChecked: (botId, conversationId, text, options) => deliveryService.postConversationChecked(botId, conversationId, text, options),
101
113
  echoVersion: 1,
102
114
  replyContextVersion: 1,
103
115
  replyReceiptVersion: 1,
@@ -193,6 +205,7 @@ export function createImHostPlugin(internals = {}) {
193
205
  }
194
206
  try {
195
207
  startDelivery(ctx, deliveryService, { authority: config.rpcAuthority });
208
+ if (deliveryService.appSetup) startAppSetup(ctx, deliveryService.appSetup, config.rpcAuthority);
196
209
  } catch (error) {
197
210
  logger.error?.('[dsh-im] failed to activate delivery management; continuing with channels', error);
198
211
  }