@xmanrui/dsh-im 5.8.0 → 5.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +42 -7
- package/README.md +53 -7
- package/docs/preset-workspaces.md +37 -0
- package/lib/client.js +34 -2
- package/lib/index.js +329 -326
- package/package.json +3 -1
- package/plugin-src/client/connection-error.js +1 -1
- package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
- package/plugin-src/host/channels/feishu/production.mjs +2 -1
- package/plugin-src/host/channels/matrix/production.mjs +2 -1
- package/plugin-src/host/channels/qq/production.mjs +2 -1
- package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
- package/plugin-src/host/channels/shared/production.mjs +32 -3
- package/plugin-src/host/channels/slack/production.mjs +2 -1
- package/plugin-src/host/channels/wecom/production.mjs +2 -1
- package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
- package/plugin-src/host/channels/weixin/production.mjs +2 -1
- package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
- package/plugin-src/host/delivery-adapter.mjs +122 -1
- package/plugin-src/host/delivery-service.mjs +40 -0
- package/plugin-src/host/ds-bot-client.mjs +28 -2
- package/plugin-src/host/index.mjs +24 -1
- package/plugin-src/host/modern-harness-api.mjs +3 -0
- package/scripts/telegram-menu-scopes.mjs +57 -0
- package/scripts/verify-interface-language.mjs +60 -15
- package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
- package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
- package/src/channels/email/transports/imap-smtp.mjs +21 -11
- package/src/channels/feishu/bridge.mjs +46 -10
- package/src/channels/feishu/feishu-cards.mjs +96 -25
- package/src/channels/qq/qq-menu.mjs +3 -4
- package/src/channels/shared/action-card.mjs +331 -0
- package/src/channels/shared/bot-workspace-store.mjs +123 -8
- package/src/channels/shared/command-catalog.mjs +20 -5
- package/src/channels/shared/conversation/describe.mjs +116 -0
- package/src/channels/shared/conversation-state-store.mjs +62 -0
- package/src/channels/shared/diagnostic-details.mjs +38 -0
- package/src/channels/shared/harness-approval.mjs +58 -13
- package/src/channels/shared/harness-client.mjs +13 -0
- package/src/channels/shared/harness-session-binding.mjs +13 -1
- package/src/channels/shared/i18n-en/feishu.mjs +6 -0
- package/src/channels/shared/i18n-en/shared-a.mjs +9 -0
- package/src/channels/shared/i18n-en/telegram.mjs +14 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
- package/src/channels/shared/i18n-ru/shared-a.mjs +9 -0
- package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
- package/src/channels/shared/model-command.mjs +5 -0
- package/src/channels/shared/preset-workspaces.mjs +48 -0
- package/src/channels/shared/qr-encoding-error.mjs +8 -2
- package/src/channels/shared/status-command.mjs +159 -0
- package/src/channels/shared/text-harness-bridge.mjs +86 -4
- package/src/channels/shared/workspace-command.mjs +20 -12
- package/src/channels/shared/workspace-session.mjs +30 -5
- package/src/channels/telegram/approval-card.mjs +379 -0
- package/src/channels/telegram/telegram-api.mjs +10 -1
- package/src/channels/telegram/telegram-bridge.mjs +7 -0
- package/src/channels/telegram/telegram-runtime.mjs +125 -13
- package/src/channels/wecom/wecom-bridge.mjs +5 -3
|
@@ -19,9 +19,12 @@ import { workspaceLabels } from '../shared/workspace-labels.mjs';
|
|
|
19
19
|
import { normalizeFeishuStepCardPanels } from './step-push-mode.mjs';
|
|
20
20
|
|
|
21
21
|
export const MENU_PAGE_SIZE = 10;
|
|
22
|
+
export const MODEL_PAGE_SIZE = 20;
|
|
23
|
+
const MODEL_CARD_TEXT_LIMIT = 200;
|
|
22
24
|
|
|
23
25
|
/** 预设下拉中「跟随默认」(null) 的哨兵值,供 initial_index 命中与回调识别。 */
|
|
24
26
|
export const PRESET_FOLLOW_DEFAULT_SENTINEL = '__preset_follow_default__';
|
|
27
|
+
export const REASONING_DEFAULT_SENTINEL = '__reasoning_default__';
|
|
25
28
|
|
|
26
29
|
function plainText(content) {
|
|
27
30
|
return { tag: 'plain_text', content: String(content) };
|
|
@@ -240,10 +243,19 @@ export function menuCard(ctx) {
|
|
|
240
243
|
const curModelId = curModel ? `${curModel.provider}/${curModel.model}` : null;
|
|
241
244
|
const flat = [];
|
|
242
245
|
for (const group of groups) {
|
|
243
|
-
for (const model of (group.models || []))
|
|
246
|
+
for (const model of (group.models || [])) {
|
|
247
|
+
flat.push({
|
|
248
|
+
id: `${group.id}/${model.id}`,
|
|
249
|
+
name: `${group.name} - ${model.name}`,
|
|
250
|
+
reasoning: model.reasoning,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
244
253
|
}
|
|
245
254
|
let modelDropdown = null;
|
|
255
|
+
let reasoningDropdown = null;
|
|
246
256
|
if (flat.length > 1) {
|
|
257
|
+
// Keep the compact menu within Feishu select limits; the dedicated model
|
|
258
|
+
// card exposes the complete catalog.
|
|
247
259
|
const setModelOptions = flat.slice(0, 30).map((opt) => ({
|
|
248
260
|
text: { tag: 'plain_text', content: `${opt.id === curModelId ? '✓ ' : ''}${opt.name}` },
|
|
249
261
|
value: opt.id,
|
|
@@ -257,6 +269,28 @@ export function menuCard(ctx) {
|
|
|
257
269
|
behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
|
|
258
270
|
};
|
|
259
271
|
}
|
|
272
|
+
const selectedModel = flat.find((opt) => opt.id === curModelId);
|
|
273
|
+
const efforts = Array.isArray(selectedModel?.reasoning?.efforts)
|
|
274
|
+
? selectedModel.reasoning.efforts.filter((effort) => typeof effort?.id === 'string' && effort.id)
|
|
275
|
+
: [];
|
|
276
|
+
if (efforts.length > 0) {
|
|
277
|
+
const currentEffort = curModel?.reasoningEffort ?? selectedModel.reasoning.defaultEffort;
|
|
278
|
+
const effortOptions = [
|
|
279
|
+
{ id: REASONING_DEFAULT_SENTINEL, name: t('默认等级') },
|
|
280
|
+
...efforts.map((effort) => ({ id: effort.id, name: effort.name || effort.id })),
|
|
281
|
+
].map((effort) => ({
|
|
282
|
+
text: { tag: 'plain_text', content: `${effort.id === (currentEffort ?? REASONING_DEFAULT_SENTINEL) ? '✓ ' : ''}${effort.name}` },
|
|
283
|
+
value: effort.id,
|
|
284
|
+
}));
|
|
285
|
+
reasoningDropdown = {
|
|
286
|
+
tag: 'select_static',
|
|
287
|
+
name: 'reasoning_pick',
|
|
288
|
+
placeholder: { tag: 'plain_text', content: t('切换推理等级') },
|
|
289
|
+
initial_index: initialIndex(effortOptions, currentEffort ?? REASONING_DEFAULT_SENTINEL),
|
|
290
|
+
options: effortOptions,
|
|
291
|
+
behaviors: [{ type: 'callback', value: { action: 'reasoning_pick' } }],
|
|
292
|
+
};
|
|
293
|
+
}
|
|
260
294
|
|
|
261
295
|
// 渲染 2×2 网格:图标 + 下拉并列
|
|
262
296
|
// 每一行用 4 列 column_set:图标 | 下拉 | 图标 | 下拉
|
|
@@ -291,6 +325,12 @@ export function menuCard(ctx) {
|
|
|
291
325
|
tag: 'column_set', flex_mode: 'none',
|
|
292
326
|
columns: [iconCol('🤖'), dropdownCol(row2[0]), iconCol('🧠'), dropdownCol(row2[1])],
|
|
293
327
|
});
|
|
328
|
+
if (reasoningDropdown) {
|
|
329
|
+
elements.push({
|
|
330
|
+
tag: 'column_set', flex_mode: 'none',
|
|
331
|
+
columns: [iconCol('🧠'), dropdownCol(reasoningDropdown)],
|
|
332
|
+
});
|
|
333
|
+
}
|
|
294
334
|
|
|
295
335
|
// 新会话 + 全部会话按钮
|
|
296
336
|
const sessionButtons = buttonPair(newSessionLabel, 'new', t('📋 会话/关注'), 'sessions');
|
|
@@ -419,46 +459,52 @@ export function presetCard(catalog) {
|
|
|
419
459
|
* The catalog comes from `harness.listModels()` or `session.models()`.
|
|
420
460
|
* Groups are shown as text, then a flat dropdown for selection.
|
|
421
461
|
*/
|
|
422
|
-
export function modelCard(catalog) {
|
|
462
|
+
export function modelCard(catalog, { page = 0 } = {}) {
|
|
423
463
|
const { groups, current } = catalog;
|
|
424
464
|
const currentId = current ? `${current.provider}/${current.model}` : null;
|
|
465
|
+
const allModels = groups.flatMap((group) => group.models.map((model) => ({
|
|
466
|
+
group, model, id: `${group.id}/${model.id}`,
|
|
467
|
+
})));
|
|
468
|
+
const pages = Math.max(1, Math.ceil(allModels.length / MODEL_PAGE_SIZE));
|
|
469
|
+
const selectedPage = Number.isSafeInteger(page) && page >= 0 ? Math.min(page, pages - 1) : 0;
|
|
470
|
+
const currentOrdinal = currentId ? allModels.findIndex((entry) => entry.id === currentId) : -1;
|
|
471
|
+
const visibleModels = allModels.slice(selectedPage * MODEL_PAGE_SIZE, (selectedPage + 1) * MODEL_PAGE_SIZE);
|
|
425
472
|
|
|
426
473
|
const elements = [
|
|
427
474
|
{ tag: 'div', text: markdown(t('**当前模型**:{model}', { model: currentId || t('未设置') })) },
|
|
428
475
|
{ tag: 'hr' },
|
|
429
476
|
];
|
|
430
477
|
|
|
431
|
-
|
|
432
|
-
let total = 0;
|
|
433
|
-
for (const group of groups) total += group.models.length;
|
|
434
|
-
|
|
435
|
-
if (total === 0) {
|
|
478
|
+
if (allModels.length === 0) {
|
|
436
479
|
elements.push(
|
|
437
480
|
{ tag: 'div', text: markdown(t('当前没有可用模型。')) },
|
|
438
481
|
backButton(),
|
|
439
482
|
);
|
|
440
483
|
} else {
|
|
441
|
-
|
|
484
|
+
const currentUnavailable = currentId && currentOrdinal < 0;
|
|
485
|
+
elements.push({ tag: 'div', text: markdown(t('第 {page}/{pages} 页 · 共 {total} 个模型', {
|
|
486
|
+
page: selectedPage + 1, pages, total: allModels.length,
|
|
487
|
+
})) });
|
|
488
|
+
if (currentUnavailable) elements.push({ tag: 'div', text: markdown(t('当前模型不可用:{model}', { model: currentId })) });
|
|
489
|
+
// Bound the Markdown and the picker together, so a large catalog does not
|
|
490
|
+
// produce an oversized card or silently hide selectable entries.
|
|
442
491
|
for (const group of groups) {
|
|
443
|
-
const modelLines = group.
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
elements.push(
|
|
492
|
+
const modelLines = visibleModels.filter((entry) => entry.group === group).map(({ id }) => (
|
|
493
|
+
`${id}${id === currentId ? ' ✓' : ''}`
|
|
494
|
+
));
|
|
495
|
+
if (modelLines.length) elements.push(
|
|
448
496
|
{ tag: 'div', text: markdown(`**${group.name}**\n${modelLines.join('\n')}`) },
|
|
449
497
|
);
|
|
450
498
|
}
|
|
451
499
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
}
|
|
461
|
-
}
|
|
500
|
+
const allOptions = visibleModels.map(({ group, model, id }) => ({
|
|
501
|
+
value: id,
|
|
502
|
+
text: { tag: 'plain_text', content: `${group.name} - ${model.name}`.slice(0, MODEL_CARD_TEXT_LIMIT) },
|
|
503
|
+
}));
|
|
504
|
+
const currentOption = allModels.find((entry) => entry.id === currentId)?.model;
|
|
505
|
+
const efforts = Array.isArray(currentOption?.reasoning?.efforts)
|
|
506
|
+
? currentOption.reasoning.efforts.filter((effort) => typeof effort?.id === 'string' && effort.id)
|
|
507
|
+
: [];
|
|
462
508
|
|
|
463
509
|
elements.push(
|
|
464
510
|
{ tag: 'hr' },
|
|
@@ -473,9 +519,34 @@ export function modelCard(catalog) {
|
|
|
473
519
|
})),
|
|
474
520
|
behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
|
|
475
521
|
},
|
|
476
|
-
{ tag: 'hr' },
|
|
477
|
-
backButton(),
|
|
478
522
|
);
|
|
523
|
+
if (efforts.length > 0) {
|
|
524
|
+
const currentEffort = current?.reasoningEffort ?? currentOption.reasoning.defaultEffort;
|
|
525
|
+
const effortOptions = [
|
|
526
|
+
{ id: REASONING_DEFAULT_SENTINEL, name: t('默认等级') },
|
|
527
|
+
...efforts.map((effort) => ({ id: effort.id, name: effort.name || effort.id })),
|
|
528
|
+
].map((effort) => ({
|
|
529
|
+
text: { tag: 'plain_text', content: `${effort.id === (currentEffort ?? REASONING_DEFAULT_SENTINEL) ? '✓ ' : ''}${effort.name}` },
|
|
530
|
+
value: effort.id,
|
|
531
|
+
}));
|
|
532
|
+
elements.push({
|
|
533
|
+
tag: 'select_static',
|
|
534
|
+
name: 'reasoning_pick',
|
|
535
|
+
placeholder: { tag: 'plain_text', content: t('切换推理等级') },
|
|
536
|
+
initial_index: initialIndex(effortOptions, currentEffort ?? REASONING_DEFAULT_SENTINEL),
|
|
537
|
+
options: effortOptions,
|
|
538
|
+
behaviors: [{ type: 'callback', value: { action: 'reasoning_pick' } }],
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
if (pages > 1) {
|
|
542
|
+
elements.push(buttonPair(
|
|
543
|
+
selectedPage > 0 ? t('◀ 上一页') : t('第一页'),
|
|
544
|
+
selectedPage > 0 ? `models:${selectedPage - 1}` : 'models:0',
|
|
545
|
+
selectedPage + 1 < pages ? t('下一页 ▶') : t('最后一页'),
|
|
546
|
+
selectedPage + 1 < pages ? `models:${selectedPage + 1}` : `models:${pages - 1}`,
|
|
547
|
+
));
|
|
548
|
+
}
|
|
549
|
+
elements.push({ tag: 'hr' }, backButton());
|
|
479
550
|
}
|
|
480
551
|
return cardWith(t('🧠 模型列表'), elements);
|
|
481
552
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { ApiError } from '@tencent-connect/qqbot-nodejs';
|
|
3
|
-
import { workspacePathSnapshot } from '../shared/workspace-command.mjs';
|
|
3
|
+
import { conversationSessionWorkspace, workspacePathSnapshot } from '../shared/workspace-command.mjs';
|
|
4
4
|
import { t } from '../shared/i18n.mjs';
|
|
5
5
|
|
|
6
6
|
export const QQ_MENU_TTL_MS = 15 * 60_000;
|
|
@@ -88,8 +88,7 @@ async function catalogFor(harness, sessionId, key, options) {
|
|
|
88
88
|
|
|
89
89
|
export async function qqMenuView(name, harness, state, key, { signal, busy = false } = {}) {
|
|
90
90
|
const workspace = harness.currentWorkspace?.();
|
|
91
|
-
const sessionWorkspace =
|
|
92
|
-
? harness.currentConversationWorkspace(key) : workspace;
|
|
91
|
+
const sessionWorkspace = await conversationSessionWorkspace(harness, key, { signal });
|
|
93
92
|
const sessionId = state.sessionFor(key);
|
|
94
93
|
const options = { signal };
|
|
95
94
|
const archived = state.includesArchivedSessions?.() === true;
|
|
@@ -97,7 +96,7 @@ export async function qqMenuView(name, harness, state, key, { signal, busy = fal
|
|
|
97
96
|
if (name === 'main' || name === 'status') {
|
|
98
97
|
if (name === 'status') await harness.ensureRunning(options);
|
|
99
98
|
const results = await Promise.allSettled([
|
|
100
|
-
harness.listWorkspaceSessions?.(
|
|
99
|
+
harness.listWorkspaceSessions?.(sessionWorkspace, options),
|
|
101
100
|
catalogFor(harness, sessionId, key, options),
|
|
102
101
|
harness.agentPresetSettings?.(options),
|
|
103
102
|
]);
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { t } from './i18n.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Shared foundation for interactive cards that carry a one-shot button press.
|
|
7
|
+
*
|
|
8
|
+
* Every carded channel needs the same four things, and four independent
|
|
9
|
+
* implementations already existed (Feishu card keys, QQ opaque tokens, DingTalk
|
|
10
|
+
* revisions, Telegram question nonces). This module provides them once:
|
|
11
|
+
*
|
|
12
|
+
* - a versioned, bounded callback namespace (`<prefix>|<nonce>|<action>`) so a
|
|
13
|
+
* keyboard press is attributable to exactly one presentation;
|
|
14
|
+
* - a nonce registry with TTL and capacity limits, so a dead card cannot grow
|
|
15
|
+
* memory forever;
|
|
16
|
+
* - a synchronous first-press claim, so two taps (or two clients) execute once;
|
|
17
|
+
* - one set of Chinese notices for pressed/expired/superseded cards.
|
|
18
|
+
*
|
|
19
|
+
* Cards that also need to re-check live data (a list shrank, a session was
|
|
20
|
+
* deleted) should `claim()` first and then `settle(nonce, 'stale')` when the
|
|
21
|
+
* re-check fails.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Telegram rejects callback_data longer than 64 bytes. */
|
|
25
|
+
export const ACTION_CARD_CALLBACK_MAX_BYTES = 64;
|
|
26
|
+
|
|
27
|
+
const CALLBACK_PREFIX_PATTERN = /^[a-z][a-z0-9]{0,7}$/u;
|
|
28
|
+
const NONCE_PATTERN = /^[A-Za-z0-9_-]{1,32}$/u;
|
|
29
|
+
const ACTION_PATTERN = /^[A-Za-z0-9_-]{1,16}$/u;
|
|
30
|
+
const DEFAULT_NONCE_BYTES = 9;
|
|
31
|
+
|
|
32
|
+
export const ACTION_CARD_STATUS = Object.freeze({
|
|
33
|
+
/** Rendered, waiting for its first press. */
|
|
34
|
+
ACTIVE: 'active',
|
|
35
|
+
/** Pressed; the handler owns the outcome now. */
|
|
36
|
+
CLAIMED: 'claimed',
|
|
37
|
+
/** Handled successfully. */
|
|
38
|
+
RESOLVED: 'resolved',
|
|
39
|
+
/** TTL elapsed (approval timeout, dead keyboard). */
|
|
40
|
+
EXPIRED: 'expired',
|
|
41
|
+
/** A newer card replaced this one in the same conversation. */
|
|
42
|
+
SUPERSEDED: 'superseded',
|
|
43
|
+
/** The live re-check after a press found the underlying state changed. */
|
|
44
|
+
STALE: 'stale',
|
|
45
|
+
/** The owner revoked the card (route closed, approval withdrawn). */
|
|
46
|
+
REVOKED: 'revoked',
|
|
47
|
+
/** No such nonce (process restarted, foreign payload). */
|
|
48
|
+
UNKNOWN: 'unknown',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const LIVE_STATUSES = new Set([ACTION_CARD_STATUS.ACTIVE, ACTION_CARD_STATUS.CLAIMED]);
|
|
52
|
+
const TERMINAL_STATUSES = new Set([
|
|
53
|
+
ACTION_CARD_STATUS.RESOLVED,
|
|
54
|
+
ACTION_CARD_STATUS.EXPIRED,
|
|
55
|
+
ACTION_CARD_STATUS.SUPERSEDED,
|
|
56
|
+
ACTION_CARD_STATUS.STALE,
|
|
57
|
+
ACTION_CARD_STATUS.REVOKED,
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
/** One notice per card state; channels override the wording per surface. */
|
|
61
|
+
export const ACTION_CARD_STATE_TEXTS = Object.freeze({
|
|
62
|
+
[ACTION_CARD_STATUS.ACTIVE]: '正在处理,请稍候。',
|
|
63
|
+
[ACTION_CARD_STATUS.CLAIMED]: '正在提交,请稍候。',
|
|
64
|
+
[ACTION_CARD_STATUS.RESOLVED]: '该操作已处理,无需重复操作。',
|
|
65
|
+
[ACTION_CARD_STATUS.EXPIRED]: '该操作已过期,请重新打开。',
|
|
66
|
+
[ACTION_CARD_STATUS.SUPERSEDED]: '该操作已被新操作取代,请使用最新一条。',
|
|
67
|
+
[ACTION_CARD_STATUS.STALE]: '该内容已变化,请重新打开后再操作。',
|
|
68
|
+
[ACTION_CARD_STATUS.REVOKED]: '该操作已失效,请重新打开。',
|
|
69
|
+
[ACTION_CARD_STATUS.UNKNOWN]: '该操作已失效或不存在。',
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* A random, URL-safe presentation identity.
|
|
74
|
+
* 9 bytes → 12 base64url characters: collision-safe per conversation and small
|
|
75
|
+
* enough that the whole callback payload stays far under 64 bytes.
|
|
76
|
+
*/
|
|
77
|
+
export function createActionNonce(byteLength = DEFAULT_NONCE_BYTES) {
|
|
78
|
+
if (!Number.isInteger(byteLength) || byteLength < 1 || byteLength > 24) {
|
|
79
|
+
throw new TypeError('An action card nonce needs 1..24 random bytes');
|
|
80
|
+
}
|
|
81
|
+
return randomBytes(byteLength).toString('base64url');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Build one versioned callback namespace, e.g. `ap1|<nonce>|<action>`.
|
|
86
|
+
* Encoding validates every token before emitting it, so a button can always be
|
|
87
|
+
* attributed and can never exceed Telegram's callback budget.
|
|
88
|
+
*/
|
|
89
|
+
export function createCallbackNamespace(prefix) {
|
|
90
|
+
if (typeof prefix !== 'string' || !CALLBACK_PREFIX_PATTERN.test(prefix)) {
|
|
91
|
+
throw new TypeError('An action card callback prefix is invalid');
|
|
92
|
+
}
|
|
93
|
+
const maxBytes = ACTION_CARD_CALLBACK_MAX_BYTES;
|
|
94
|
+
return Object.freeze({
|
|
95
|
+
prefix,
|
|
96
|
+
maxBytes,
|
|
97
|
+
encode({ nonce, action } = {}) {
|
|
98
|
+
if (typeof nonce !== 'string' || !NONCE_PATTERN.test(nonce)) {
|
|
99
|
+
throw new TypeError('An action card nonce is invalid');
|
|
100
|
+
}
|
|
101
|
+
if (typeof action !== 'string' || !ACTION_PATTERN.test(action)) {
|
|
102
|
+
throw new TypeError('An action card action is invalid');
|
|
103
|
+
}
|
|
104
|
+
const data = `${prefix}|${nonce}|${action}`;
|
|
105
|
+
if (Buffer.byteLength(data, 'utf8') > maxBytes) {
|
|
106
|
+
throw new TypeError(`An action card callback must be at most ${maxBytes} bytes`);
|
|
107
|
+
}
|
|
108
|
+
return data;
|
|
109
|
+
},
|
|
110
|
+
parse(data) {
|
|
111
|
+
if (typeof data !== 'string') return null;
|
|
112
|
+
const parts = data.split('|');
|
|
113
|
+
if (parts.length !== 3 || parts[0] !== prefix) return null;
|
|
114
|
+
const [, nonce, action] = parts;
|
|
115
|
+
if (!NONCE_PATTERN.test(nonce) || !ACTION_PATTERN.test(action)) return null;
|
|
116
|
+
return { nonce, action };
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The notice shown for a dead or already-handled card. */
|
|
122
|
+
export function actionCardStateText(status, texts = {}) {
|
|
123
|
+
const override = texts && typeof texts === 'object' ? texts[status] : undefined;
|
|
124
|
+
const fallback = ACTION_CARD_STATE_TEXTS[status]
|
|
125
|
+
?? (texts && typeof texts === 'object' ? texts[ACTION_CARD_STATUS.UNKNOWN] : undefined)
|
|
126
|
+
?? ACTION_CARD_STATE_TEXTS[ACTION_CARD_STATUS.UNKNOWN];
|
|
127
|
+
return t(typeof override === 'string' && override ? override : fallback);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* In-memory presentation registry for one channel.
|
|
132
|
+
*
|
|
133
|
+
* Entries live for `ttlMs`; a terminal entry is kept until then so a late press
|
|
134
|
+
* still gets "已处理/已过期" instead of a generic "不存在". At most
|
|
135
|
+
* `maxEntries` cards are remembered (oldest is evicted first) and a new card in
|
|
136
|
+
* a conversation supersedes the previous live one.
|
|
137
|
+
*/
|
|
138
|
+
export class ActionCardRegistry {
|
|
139
|
+
#ttlMs;
|
|
140
|
+
#maxEntries;
|
|
141
|
+
#now;
|
|
142
|
+
#createNonce;
|
|
143
|
+
#entries = new Map();
|
|
144
|
+
|
|
145
|
+
constructor({
|
|
146
|
+
ttlMs = 3_600_000,
|
|
147
|
+
maxEntries = 256,
|
|
148
|
+
now = Date.now,
|
|
149
|
+
createNonce = createActionNonce,
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
152
|
+
throw new TypeError('An action card TTL must be a positive number');
|
|
153
|
+
}
|
|
154
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
|
|
155
|
+
throw new TypeError('An action card capacity must be a positive integer');
|
|
156
|
+
}
|
|
157
|
+
if (typeof now !== 'function') throw new TypeError('An action card clock must be a function');
|
|
158
|
+
if (typeof createNonce !== 'function') {
|
|
159
|
+
throw new TypeError('An action card nonce factory must be a function');
|
|
160
|
+
}
|
|
161
|
+
this.#ttlMs = ttlMs;
|
|
162
|
+
this.#maxEntries = maxEntries;
|
|
163
|
+
this.#now = now;
|
|
164
|
+
this.#createNonce = createNonce;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
get size() {
|
|
168
|
+
return this.#entries.size;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Register one presentation. Issuing a new card in the same conversation
|
|
173
|
+
* retires the previous live one — one conversation shows one working card.
|
|
174
|
+
*/
|
|
175
|
+
issue({ conversationKey, kind = '', payload = {}, ttlMs } = {}) {
|
|
176
|
+
const key = typeof conversationKey === 'string' ? conversationKey.trim() : '';
|
|
177
|
+
if (!key) throw new TypeError('An action card requires a conversation key');
|
|
178
|
+
const now = this.#now();
|
|
179
|
+
const lifetime = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : this.#ttlMs;
|
|
180
|
+
// Drop long-dead cards so TTL memory is reclaimed even when presses stop.
|
|
181
|
+
this.purge();
|
|
182
|
+
this.revokeConversation(key, { status: ACTION_CARD_STATUS.SUPERSEDED });
|
|
183
|
+
|
|
184
|
+
let nonce = null;
|
|
185
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
186
|
+
const candidate = this.#createNonce();
|
|
187
|
+
if (typeof candidate !== 'string' || !NONCE_PATTERN.test(candidate)) {
|
|
188
|
+
throw new TypeError('An action card nonce must be 1..32 URL-safe characters');
|
|
189
|
+
}
|
|
190
|
+
if (!this.#entries.has(candidate)) {
|
|
191
|
+
nonce = candidate;
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (nonce === null) throw new Error('Could not allocate a unique action card nonce');
|
|
196
|
+
|
|
197
|
+
const entry = {
|
|
198
|
+
nonce,
|
|
199
|
+
conversationKey: key,
|
|
200
|
+
kind: typeof kind === 'string' ? kind : '',
|
|
201
|
+
payload: payload && typeof payload === 'object' ? payload : {},
|
|
202
|
+
status: ACTION_CARD_STATUS.ACTIVE,
|
|
203
|
+
createdAt: now,
|
|
204
|
+
expiresAt: now + lifetime,
|
|
205
|
+
claimedAt: null,
|
|
206
|
+
settledAt: null,
|
|
207
|
+
};
|
|
208
|
+
this.#entries.set(nonce, entry);
|
|
209
|
+
this.#enforceCapacity();
|
|
210
|
+
return entry;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Read an entry (and lazily mark it expired when its TTL elapsed). */
|
|
214
|
+
get(nonce) {
|
|
215
|
+
const entry = this.#lookup(nonce);
|
|
216
|
+
if (!entry) return null;
|
|
217
|
+
this.#expireIfNeeded(entry);
|
|
218
|
+
return entry;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Claim the first press synchronously. The caller must call this before its
|
|
223
|
+
* first `await`, so a second tap cannot also see the card as active.
|
|
224
|
+
*/
|
|
225
|
+
claim(nonce) {
|
|
226
|
+
const entry = this.#lookup(nonce);
|
|
227
|
+
if (!entry) return { status: ACTION_CARD_STATUS.UNKNOWN, entry: null };
|
|
228
|
+
this.#expireIfNeeded(entry);
|
|
229
|
+
const liveStatus = entry.status;
|
|
230
|
+
if (liveStatus === ACTION_CARD_STATUS.ACTIVE) {
|
|
231
|
+
entry.status = ACTION_CARD_STATUS.CLAIMED;
|
|
232
|
+
entry.claimedAt = this.#now();
|
|
233
|
+
}
|
|
234
|
+
// `active` means this caller won the claim; any other value is a refusal.
|
|
235
|
+
return { status: liveStatus, entry };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Give a claimed card its keyboard back after a submission that failed but is
|
|
240
|
+
* still retryable (a transient RPC error, a dropped response). Without this a
|
|
241
|
+
* card stays `claimed` forever and every later press is answered with "still
|
|
242
|
+
* submitting", so the only recovery is typing the decision as text.
|
|
243
|
+
*
|
|
244
|
+
* Only a live claim can be released: a card already resolved, expired or
|
|
245
|
+
* superseded must stay dead, otherwise a stale tap could decide a newer
|
|
246
|
+
* approval. Returns the released entry, or null when nothing was released.
|
|
247
|
+
*/
|
|
248
|
+
releaseClaim(nonce) {
|
|
249
|
+
const entry = this.#lookup(nonce);
|
|
250
|
+
if (!entry) return null;
|
|
251
|
+
this.#expireIfNeeded(entry);
|
|
252
|
+
if (entry.status !== ACTION_CARD_STATUS.CLAIMED) return null;
|
|
253
|
+
entry.status = ACTION_CARD_STATUS.ACTIVE;
|
|
254
|
+
entry.claimedAt = null;
|
|
255
|
+
return entry;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Move a live card to a terminal state. Returns false when there is nothing
|
|
260
|
+
* left to settle (unknown, expired, or already settled).
|
|
261
|
+
*/
|
|
262
|
+
settle(nonce, status = ACTION_CARD_STATUS.RESOLVED) {
|
|
263
|
+
if (!TERMINAL_STATUSES.has(status)) {
|
|
264
|
+
throw new TypeError('An action card can only settle to a terminal status');
|
|
265
|
+
}
|
|
266
|
+
const entry = this.#lookup(nonce);
|
|
267
|
+
if (!entry) return false;
|
|
268
|
+
this.#expireIfNeeded(entry);
|
|
269
|
+
if (!LIVE_STATUSES.has(entry.status)) return false;
|
|
270
|
+
entry.status = status;
|
|
271
|
+
entry.settledAt = this.#now();
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The one live card of a conversation, if any. */
|
|
276
|
+
activeFor(conversationKey) {
|
|
277
|
+
for (const entry of this.#entries.values()) {
|
|
278
|
+
if (entry.conversationKey !== conversationKey) continue;
|
|
279
|
+
this.#expireIfNeeded(entry);
|
|
280
|
+
if (LIVE_STATUSES.has(entry.status)) return entry;
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Retire every live card of one conversation (route closed, list changed). */
|
|
286
|
+
revokeConversation(conversationKey, { status = ACTION_CARD_STATUS.SUPERSEDED } = {}) {
|
|
287
|
+
if (!TERMINAL_STATUSES.has(status)) {
|
|
288
|
+
throw new TypeError('An action card can only be revoked to a terminal status');
|
|
289
|
+
}
|
|
290
|
+
let revoked = 0;
|
|
291
|
+
for (const entry of this.#entries.values()) {
|
|
292
|
+
if (entry.conversationKey !== conversationKey) continue;
|
|
293
|
+
this.#expireIfNeeded(entry);
|
|
294
|
+
if (!LIVE_STATUSES.has(entry.status)) continue;
|
|
295
|
+
entry.status = status;
|
|
296
|
+
entry.settledAt = this.#now();
|
|
297
|
+
revoked += 1;
|
|
298
|
+
}
|
|
299
|
+
return revoked;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Drop every entry whose TTL elapsed; returns how many were removed. */
|
|
303
|
+
purge() {
|
|
304
|
+
const now = this.#now();
|
|
305
|
+
let removed = 0;
|
|
306
|
+
for (const [nonce, entry] of this.#entries) {
|
|
307
|
+
if (now >= entry.expiresAt) {
|
|
308
|
+
this.#entries.delete(nonce);
|
|
309
|
+
removed += 1;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return removed;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
#lookup(nonce) {
|
|
316
|
+
return typeof nonce === 'string' ? this.#entries.get(nonce) ?? null : null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
#expireIfNeeded(entry) {
|
|
320
|
+
if (!LIVE_STATUSES.has(entry.status)) return;
|
|
321
|
+
if (this.#now() < entry.expiresAt) return;
|
|
322
|
+
entry.status = ACTION_CARD_STATUS.EXPIRED;
|
|
323
|
+
entry.settledAt = entry.expiresAt;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
#enforceCapacity() {
|
|
327
|
+
while (this.#entries.size > this.#maxEntries) {
|
|
328
|
+
this.#entries.delete(this.#entries.keys().next().value);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|