@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
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
enhanceContextContent,
|
|
15
15
|
} from './context-enhancement.mjs';
|
|
16
16
|
import { runWorkspaceCommand, workspaceSwitchFailureText } from './workspace-command.mjs';
|
|
17
|
+
import { runStatusCommand } from './status-command.mjs';
|
|
17
18
|
import { runCompactCommand } from './compact-command.mjs';
|
|
18
19
|
import { isClearCommand, runClearCommand } from './clear-command.mjs';
|
|
19
20
|
import { isHistoryCommand, runHistoryCommand } from './history-command.mjs';
|
|
@@ -214,6 +215,9 @@ export class TextHarnessBridge {
|
|
|
214
215
|
#workspaceCards = new Map();
|
|
215
216
|
// Conversation key → the one picker card that is still authoritative there.
|
|
216
217
|
#workspaceCardKeys = new Map();
|
|
218
|
+
// Optional channel-supplied approval card controller (see HarnessApprovalQueue's
|
|
219
|
+
// render hook). Null keeps every channel's existing plain-text approval flow.
|
|
220
|
+
#approvalCard;
|
|
217
221
|
#contextHooks = null;
|
|
218
222
|
// Delivery attempts per message id. A failed turn releases its `markSeen` so
|
|
219
223
|
// the next poll can retry, and this counter is what keeps that from becoming
|
|
@@ -242,6 +246,8 @@ export class TextHarnessBridge {
|
|
|
242
246
|
keepaliveIntervalMs = 4_000,
|
|
243
247
|
interactionCard = null,
|
|
244
248
|
workspaceCard = null,
|
|
249
|
+
approvalCard = null,
|
|
250
|
+
approvalTimeoutMs,
|
|
245
251
|
contextHooks = null,
|
|
246
252
|
autoSteerSameSender = false,
|
|
247
253
|
autoSteerLimit = 0,
|
|
@@ -264,6 +270,7 @@ export class TextHarnessBridge {
|
|
|
264
270
|
this.#keepaliveIntervalMs = keepaliveIntervalMs;
|
|
265
271
|
this.#interactionCard = interactionCard ?? null;
|
|
266
272
|
this.#workspaceCard = workspaceCard ?? null;
|
|
273
|
+
this.#approvalCard = approvalCard ?? null;
|
|
267
274
|
// Opt-in follow-up lanes for channels whose groups run on rapid consecutive
|
|
268
275
|
// posts: fold a same sender's burst into one dispatch, and steer that
|
|
269
276
|
// sender's own mid-turn follow-ups into the in-flight turn instead of
|
|
@@ -287,6 +294,10 @@ export class TextHarnessBridge {
|
|
|
287
294
|
this.#approvals = new HarnessApprovalQueue({
|
|
288
295
|
label: descriptor.key,
|
|
289
296
|
logger,
|
|
297
|
+
// Tests and hosts may shorten the approval deadline; the default stays.
|
|
298
|
+
...(Number.isFinite(approvalTimeoutMs) && approvalTimeoutMs > 0
|
|
299
|
+
? { approvalTimeoutMs }
|
|
300
|
+
: {}),
|
|
290
301
|
});
|
|
291
302
|
// A queued message lives only in #queues. If the process dies before its
|
|
292
303
|
// turn runs the user has already been told it is queued, so the persisted
|
|
@@ -1125,8 +1136,14 @@ export class TextHarnessBridge {
|
|
|
1125
1136
|
return;
|
|
1126
1137
|
}
|
|
1127
1138
|
if (!hasImages && !hasFiles && command === '/status') {
|
|
1128
|
-
await
|
|
1129
|
-
|
|
1139
|
+
const status = await runStatusCommand({
|
|
1140
|
+
descriptor: this.#descriptor,
|
|
1141
|
+
harness: this.#harness,
|
|
1142
|
+
state: this.#state,
|
|
1143
|
+
conversationKey,
|
|
1144
|
+
signal: this.#signal,
|
|
1145
|
+
});
|
|
1146
|
+
await this.#bot.sendText(target, status.message);
|
|
1130
1147
|
return;
|
|
1131
1148
|
}
|
|
1132
1149
|
const workspaceCommand = !hasImages && !hasFiles
|
|
@@ -1224,9 +1241,12 @@ export class TextHarnessBridge {
|
|
|
1224
1241
|
if (message.kind === 'group') content = prependSpeakerLabel(content, message.speakerName);
|
|
1225
1242
|
const snapshot = this.#acceptedMessageIds.get(messageId);
|
|
1226
1243
|
let contextEnhanced = false;
|
|
1244
|
+
// contextSource() is enhancement-only: it is read here, under an enabled
|
|
1245
|
+
// snapshot, and nowhere else. The author record below reuses this read.
|
|
1246
|
+
let contextSource = null;
|
|
1227
1247
|
if (snapshot) {
|
|
1228
1248
|
const originalContent = content ?? text;
|
|
1229
|
-
|
|
1249
|
+
contextSource = message.contextSource?.() ?? null;
|
|
1230
1250
|
content = enhanceContextContent(originalContent, snapshot, () => ({
|
|
1231
1251
|
channel: this.#descriptor.key,
|
|
1232
1252
|
senderId,
|
|
@@ -1286,6 +1306,22 @@ export class TextHarnessBridge {
|
|
|
1286
1306
|
// opened: the auto-steer lane keys its authorship decision off this
|
|
1287
1307
|
// record, and the finally below retires it when the turn settles.
|
|
1288
1308
|
this.#turnAuthors.set(conversationKey, { senderId, steered: 0, turnMessageId: messageId });
|
|
1309
|
+
// Persist who spoke here last, so a later describeConversation() can name
|
|
1310
|
+
// the sender of a group turn without replaying any message text. Channels
|
|
1311
|
+
// that own a different state store simply skip it.
|
|
1312
|
+
// The sender id and bot flag are always kept. A display name is kept only
|
|
1313
|
+
// when the channel already exposes it (Matrix speakerName) or context
|
|
1314
|
+
// enhancement read it above; a disabled enhancement never leaks names.
|
|
1315
|
+
try {
|
|
1316
|
+
await this.#state.rememberAuthor?.(conversationKey, {
|
|
1317
|
+
senderId,
|
|
1318
|
+
senderName: message.senderName ?? message.speakerName ?? contextSource?.senderName,
|
|
1319
|
+
senderUsername: message.senderUsername ?? contextSource?.senderUsername,
|
|
1320
|
+
isBot: message.senderIsBot === true,
|
|
1321
|
+
});
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] unable to remember the conversation author:`, error?.message ?? error);
|
|
1324
|
+
}
|
|
1289
1325
|
// The prompt is about to enter the Harness inbox, which is itself durable.
|
|
1290
1326
|
// Marking the entry submitted first means a crash after this point reports
|
|
1291
1327
|
// the message instead of replaying a turn the Harness may already own.
|
|
@@ -1841,6 +1877,26 @@ export class TextHarnessBridge {
|
|
|
1841
1877
|
// namespace before the question bookkeeping so a press can never touch it.
|
|
1842
1878
|
const workspacePress = this.#workspaceCard?.parse?.(callback.data) ?? null;
|
|
1843
1879
|
if (workspacePress) return this.#handleWorkspaceCardPress(callback, key, workspacePress);
|
|
1880
|
+
// Approval cards own their callback namespace; every other press keeps using
|
|
1881
|
+
// the question-card path below. The card acknowledges the press itself (the
|
|
1882
|
+
// ack must be the first round-trip), so this branch runs before any other
|
|
1883
|
+
// work in acceptCallback.
|
|
1884
|
+
if (this.#approvalCard && typeof this.#approvalCard.handlePress === 'function') {
|
|
1885
|
+
const handled = await this.#approvalCard.handlePress(callback, {
|
|
1886
|
+
bot: this.#bot,
|
|
1887
|
+
answer: (text) => this.#answerInteractionCallback(callback, text),
|
|
1888
|
+
submit: (approvalId, outcome, options) => (
|
|
1889
|
+
this.#approvals.submitByApprovalId(approvalId, outcome, options)
|
|
1890
|
+
),
|
|
1891
|
+
}).catch((error) => {
|
|
1892
|
+
this.#logger.error?.(
|
|
1893
|
+
`[dsh-im:${this.#descriptor.key}] failed to handle an approval card press:`,
|
|
1894
|
+
error,
|
|
1895
|
+
);
|
|
1896
|
+
return false;
|
|
1897
|
+
});
|
|
1898
|
+
if (handled) return;
|
|
1899
|
+
}
|
|
1844
1900
|
const pending = this.#pendingInteractions.get(key);
|
|
1845
1901
|
const notice = (text) => this.#answerInteractionCallback(callback, text);
|
|
1846
1902
|
if (!pending) return notice(t('该问题已处理,无需再次选择。'));
|
|
@@ -2083,11 +2139,37 @@ export class TextHarnessBridge {
|
|
|
2083
2139
|
requiresMention,
|
|
2084
2140
|
}) {
|
|
2085
2141
|
if (interaction?.kind === 'approval') {
|
|
2142
|
+
const send = (text) => this.#bot.sendText(target, text);
|
|
2143
|
+
// Optional interactive-card presentation. The shared queue calls
|
|
2144
|
+
// `render(pending, send)` instead of the plain text when present and
|
|
2145
|
+
// `onResolved(text, outcome)` after any decision (button or typed reply).
|
|
2146
|
+
let cardContext = null;
|
|
2147
|
+
if (this.#approvalCard && typeof this.#approvalCard.createContext === 'function') {
|
|
2148
|
+
try {
|
|
2149
|
+
cardContext = this.#approvalCard.createContext({
|
|
2150
|
+
key,
|
|
2151
|
+
actor,
|
|
2152
|
+
target,
|
|
2153
|
+
send,
|
|
2154
|
+
bot: this.#bot,
|
|
2155
|
+
logger: this.#logger,
|
|
2156
|
+
});
|
|
2157
|
+
} catch (error) {
|
|
2158
|
+
this.#logger.warn?.(
|
|
2159
|
+
`[dsh-im:${this.#descriptor.key}] approval card unavailable; keeping the text approval:`,
|
|
2160
|
+
error?.message ?? error,
|
|
2161
|
+
);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2086
2164
|
return this.#approvals.handleRequested(interaction, {
|
|
2087
2165
|
key,
|
|
2088
2166
|
actor,
|
|
2089
2167
|
requiresMention,
|
|
2090
|
-
send:
|
|
2168
|
+
send: typeof cardContext?.send === 'function' ? cardContext.send : send,
|
|
2169
|
+
...(typeof cardContext?.render === 'function' ? { render: cardContext.render } : {}),
|
|
2170
|
+
...(typeof cardContext?.onResolved === 'function'
|
|
2171
|
+
? { onResolved: cardContext.onResolved }
|
|
2172
|
+
: {}),
|
|
2091
2173
|
});
|
|
2092
2174
|
}
|
|
2093
2175
|
if (interaction?.kind !== 'question') return;
|
|
@@ -115,12 +115,7 @@ async function selectedWorkspacePath(value) {
|
|
|
115
115
|
export async function workspacePathSnapshot(harness, { includeTitles = false, includeConversationDirectories = false, conversationKey, ...options } = {}) {
|
|
116
116
|
const withEntries = includeTitles && typeof harness.listWorkspaceEntries === 'function';
|
|
117
117
|
const listed = await (withEntries ? harness.listWorkspaceEntries(options) : harness.listWorkspaces(options));
|
|
118
|
-
const currentValue =
|
|
119
|
-
&& typeof conversationKey === 'string' && conversationKey
|
|
120
|
-
? harness.currentConversationWorkspace(conversationKey)
|
|
121
|
-
: typeof harness?.currentWorkspace === 'function'
|
|
122
|
-
? harness.currentWorkspace()
|
|
123
|
-
: null;
|
|
118
|
+
const currentValue = await conversationSessionWorkspace(harness, conversationKey, options);
|
|
124
119
|
const current = await existingWorkspacePath(currentValue);
|
|
125
120
|
const entries = await Promise.all((Array.isArray(listed) ? listed : []).map(async (item) => ({
|
|
126
121
|
path: await existingWorkspacePath(withEntries ? item?.path : item),
|
|
@@ -207,10 +202,21 @@ async function runWorkspaceListCommand(match, harness) {
|
|
|
207
202
|
return workspaceListingCommand(harness, { includeConversationDirectories });
|
|
208
203
|
}
|
|
209
204
|
|
|
210
|
-
async function
|
|
211
|
-
if (typeof
|
|
212
|
-
|
|
213
|
-
|
|
205
|
+
export async function conversationSessionWorkspace(harness, conversationKey, options = {}) {
|
|
206
|
+
if (typeof conversationKey === 'string' && conversationKey) {
|
|
207
|
+
if (typeof harness?.resolveConversationWorkspace === 'function') {
|
|
208
|
+
return harness.resolveConversationWorkspace(conversationKey, options);
|
|
209
|
+
}
|
|
210
|
+
if (typeof harness?.currentConversationWorkspace === 'function') {
|
|
211
|
+
return harness.currentConversationWorkspace(conversationKey);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return harness?.currentWorkspace?.() ?? null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function conversationEffectiveWorkspace(harness, conversationKey, options) {
|
|
218
|
+
if (typeof conversationKey !== 'string' || !conversationKey) return null;
|
|
219
|
+
const [current] = await existingWorkspacePaths([await conversationSessionWorkspace(harness, conversationKey, options)]);
|
|
214
220
|
harness.assertWorkspaceScope?.();
|
|
215
221
|
return current ?? null;
|
|
216
222
|
}
|
|
@@ -220,7 +226,7 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
|
|
|
220
226
|
// With no explicit selector the listing follows the conversation's effective
|
|
221
227
|
// workspace, so /conv B makes /sessionlist list B instead of the bot default.
|
|
222
228
|
if (options.conversationKey) {
|
|
223
|
-
const effective = await conversationEffectiveWorkspace(harness, options.conversationKey);
|
|
229
|
+
const effective = await conversationEffectiveWorkspace(harness, options.conversationKey, options);
|
|
224
230
|
if (effective) return { workspace: effective };
|
|
225
231
|
}
|
|
226
232
|
if (typeof harness?.currentWorkspace !== 'function') {
|
|
@@ -235,7 +241,9 @@ export async function resolveSessionListWorkspace(selector, harness, options = {
|
|
|
235
241
|
if (typeof harness?.listWorkspaces !== 'function') {
|
|
236
242
|
return { error: t('当前机器人暂不支持按序号选择工作区。') };
|
|
237
243
|
}
|
|
238
|
-
|
|
244
|
+
// Explicit workspace numbers must keep the bot-wide /workspacelist order;
|
|
245
|
+
// only a missing selector follows the bound conversation's actual group.
|
|
246
|
+
const { paths } = await workspacePathSnapshot(harness, { ...options, conversationKey: undefined });
|
|
239
247
|
const position = Number(selector);
|
|
240
248
|
if (!Number.isSafeInteger(position) || position < 1 || position > paths.length) {
|
|
241
249
|
return { error: t('工作区序号不存在,请先执行 /workspacelist。') };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
1
2
|
import { withSessionBindingLock } from './session-binding-lock.mjs';
|
|
2
3
|
import { initialSessionTitle } from './session-title.mjs';
|
|
3
4
|
import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
|
|
@@ -133,12 +134,36 @@ export async function askInWorkspaceSession({
|
|
|
133
134
|
if (dsBotSessionId) {
|
|
134
135
|
throw Object.assign(new Error('DS Bot 的当前会话不可用。'), { code: 'ds-bot-unavailable' });
|
|
135
136
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
137
|
+
// Name the Session here and bind it *before* creating it. Prompt
|
|
138
|
+
// assembly runs inside creation, and a subscriber that resolves the
|
|
139
|
+
// conversation by session id can only answer if the conversation owns
|
|
140
|
+
// the id by then.
|
|
141
|
+
// A Harness that accepts a caller-chosen id lets the binding exist
|
|
142
|
+
// before the Session does; anything else keeps the old order.
|
|
143
|
+
const plannedSessionId = harness?.canChooseSessionId === true ? `session-${randomUUID()}` : null;
|
|
144
|
+
const previousSessionId = plannedSessionId === null ? null : state.sessionFor(key) ?? null;
|
|
145
|
+
if (plannedSessionId !== null && await state.setSession(key, plannedSessionId) === false) return null;
|
|
146
|
+
try {
|
|
147
|
+
sessionId = await createSession(harness, {
|
|
148
|
+
conversationKey: key,
|
|
149
|
+
...(plannedSessionId === null ? {} : { sessionId: plannedSessionId }),
|
|
150
|
+
...(createOptions ?? {}),
|
|
151
|
+
});
|
|
152
|
+
} catch (error) {
|
|
153
|
+
// The binding must not outlive a Session that was never created, and a
|
|
154
|
+
// failed replacement must leave the previous binding in place.
|
|
155
|
+
if (plannedSessionId !== null) {
|
|
156
|
+
if (previousSessionId === null) await state.clearSession?.(key);
|
|
157
|
+
else await state.setSession(key, previousSessionId);
|
|
158
|
+
}
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
140
161
|
diagnostic.sessionId = sessionId;
|
|
141
|
-
if (
|
|
162
|
+
if (plannedSessionId === null) {
|
|
163
|
+
if (await state.setSession(key, sessionId) === false) return null;
|
|
164
|
+
} else if (sessionId !== plannedSessionId && await state.setSession(key, sessionId) === false) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
142
167
|
// Binding committed: capture the conversation's effective-workspace
|
|
143
168
|
// generation together with the session, so the prompt below is fenced
|
|
144
169
|
// against a conversation switch that only commits after the bind.
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { t } from '../shared/i18n.mjs';
|
|
2
|
+
import {
|
|
3
|
+
ACTION_CARD_STATUS,
|
|
4
|
+
ActionCardRegistry,
|
|
5
|
+
actionCardStateText,
|
|
6
|
+
createCallbackNamespace,
|
|
7
|
+
} from '../shared/action-card.mjs';
|
|
8
|
+
import { harnessApprovalText, APPROVAL_SUBMIT_RESULT } from '../shared/harness-approval.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Telegram approval buttons on top of the shared HarnessApprovalQueue `render`
|
|
12
|
+
* hook and the shared action-card foundation.
|
|
13
|
+
*
|
|
14
|
+
* A press is handled in this order, which is the whole safety story:
|
|
15
|
+
* 1. answerCallbackQuery first (the spinner stops even when the press loses);
|
|
16
|
+
* 2. actor check (only the user who started the turn can decide; a stranger
|
|
17
|
+
* gets a toast and does not consume the owner's press);
|
|
18
|
+
* 3. a synchronous first-press claim (duplicate/concurrent taps submit once);
|
|
19
|
+
* 4. submit through the shared queue, then edit the original message into a
|
|
20
|
+
* terminal receipt and clear its keyboard. `message is not modified` is
|
|
21
|
+
* success (the client already shows the receipt).
|
|
22
|
+
*
|
|
23
|
+
* The plain-text "请精准回复「批准」或「拒绝」" path is never replaced by the
|
|
24
|
+
* card: a channel without keyboard support or a refused card send falls back to
|
|
25
|
+
* the exact text the bridge sent before this feature.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** Versioned namespace so a stale `a1|`/future `ap2|` payload can never be replayed. */
|
|
29
|
+
export const TELEGRAM_APPROVAL_NAMESPACE_PREFIX = 'ap1';
|
|
30
|
+
export const TELEGRAM_APPROVAL_ACTIONS = Object.freeze({ approve: 'a', reject: 'd' });
|
|
31
|
+
export const TELEGRAM_APPROVAL_CALLBACK = createCallbackNamespace(
|
|
32
|
+
TELEGRAM_APPROVAL_NAMESPACE_PREFIX,
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const OUTCOME_BY_DECISION = Object.freeze({
|
|
36
|
+
approve: 'allowed-once',
|
|
37
|
+
reject: 'rejected',
|
|
38
|
+
});
|
|
39
|
+
const ACTION_BY_DECISION = Object.freeze({
|
|
40
|
+
approve: TELEGRAM_APPROVAL_ACTIONS.approve,
|
|
41
|
+
reject: TELEGRAM_APPROVAL_ACTIONS.reject,
|
|
42
|
+
});
|
|
43
|
+
const DECISION_BY_ACTION = Object.freeze({
|
|
44
|
+
[TELEGRAM_APPROVAL_ACTIONS.approve]: 'approve',
|
|
45
|
+
[TELEGRAM_APPROVAL_ACTIONS.reject]: 'reject',
|
|
46
|
+
});
|
|
47
|
+
const BUTTON_TEXT = Object.freeze({
|
|
48
|
+
approve: '✅ 批准一次',
|
|
49
|
+
reject: '❌ 拒绝',
|
|
50
|
+
});
|
|
51
|
+
/** The card body keeps the tool/argument summary; the buttons replace the prompt. */
|
|
52
|
+
const TERMINAL_LABEL = Object.freeze({
|
|
53
|
+
'allowed-once': '✅ 已批准(仅本次)',
|
|
54
|
+
rejected: '❌ 已拒绝',
|
|
55
|
+
expired: '⏰ 已过期',
|
|
56
|
+
unavailable: '⛔ 已失效',
|
|
57
|
+
});
|
|
58
|
+
/** Telegram rejects a single message body over this many characters. */
|
|
59
|
+
export const TELEGRAM_APPROVAL_CARD_MAX_CHARS = 4_096;
|
|
60
|
+
const EMPTY_KEYBOARD = Object.freeze({ inline_keyboard: [] });
|
|
61
|
+
const TERMINAL_STATUS_BY_OUTCOME = Object.freeze({
|
|
62
|
+
'allowed-once': ACTION_CARD_STATUS.RESOLVED,
|
|
63
|
+
rejected: ACTION_CARD_STATUS.RESOLVED,
|
|
64
|
+
expired: ACTION_CARD_STATUS.EXPIRED,
|
|
65
|
+
unavailable: ACTION_CARD_STATUS.REVOKED,
|
|
66
|
+
});
|
|
67
|
+
const DEFAULT_STATE_TEXT_OVERRIDES = Object.freeze({
|
|
68
|
+
[ACTION_CARD_STATUS.CLAIMED]: '正在提交审批决定,请稍候。',
|
|
69
|
+
[ACTION_CARD_STATUS.RESOLVED]: '该审批已处理,无需重复操作。',
|
|
70
|
+
[ACTION_CARD_STATUS.EXPIRED]: '该审批已过期,已自动拒绝。',
|
|
71
|
+
[ACTION_CARD_STATUS.SUPERSEDED]: '该审批已被新提示取代,请使用最新一条。',
|
|
72
|
+
[ACTION_CARD_STATUS.STALE]: '该审批已失效,请等待新的审批提示。',
|
|
73
|
+
[ACTION_CARD_STATUS.REVOKED]: '该审批已失效,请等待新的审批提示。',
|
|
74
|
+
[ACTION_CARD_STATUS.UNKNOWN]: '该审批已处理或不存在,无需重复操作。',
|
|
75
|
+
});
|
|
76
|
+
const APPROVAL_CARD_NOTICES = Object.freeze({
|
|
77
|
+
ownerOnly: '只有发起当前任务的用户可以处理这条审批。',
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/** Encode one approval button payload (`ap1|<nonce>|<a|d>`). */
|
|
81
|
+
export function telegramApprovalCallbackData(nonce, decision) {
|
|
82
|
+
const action = ACTION_BY_DECISION[decision];
|
|
83
|
+
if (!action) throw new TypeError('An approval decision must be approve or reject');
|
|
84
|
+
return TELEGRAM_APPROVAL_CALLBACK.encode({ nonce, action });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Parse one of our button payloads; null for anything else (question cards, etc.). */
|
|
88
|
+
export function parseTelegramApprovalCallback(data) {
|
|
89
|
+
const parsed = TELEGRAM_APPROVAL_CALLBACK.parse(data);
|
|
90
|
+
if (!parsed) return null;
|
|
91
|
+
const decision = DECISION_BY_ACTION[parsed.action];
|
|
92
|
+
if (!decision) return null;
|
|
93
|
+
return { nonce: parsed.nonce, action: decision };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The two-button keyboard for one presentation. */
|
|
97
|
+
export function telegramApprovalMarkup(nonce) {
|
|
98
|
+
return {
|
|
99
|
+
inline_keyboard: [[
|
|
100
|
+
{
|
|
101
|
+
text: t(BUTTON_TEXT.approve),
|
|
102
|
+
callback_data: telegramApprovalCallbackData(nonce, 'approve'),
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
text: t(BUTTON_TEXT.reject),
|
|
106
|
+
callback_data: telegramApprovalCallbackData(nonce, 'reject'),
|
|
107
|
+
},
|
|
108
|
+
]],
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The card body: today's approval text (tool + arguments + reason) without the
|
|
114
|
+
* "type 批准/拒绝" prompt, which a button makes obsolete. The plain-text path
|
|
115
|
+
* still uses the unmodified `harnessApprovalText` output.
|
|
116
|
+
*/
|
|
117
|
+
export function telegramApprovalCardText(pending) {
|
|
118
|
+
const text = harnessApprovalText(pending?.interaction?.payload, {
|
|
119
|
+
toolCall: pending?.toolCall,
|
|
120
|
+
requiresMention: pending?.requiresMention === true,
|
|
121
|
+
hasButtons: true,
|
|
122
|
+
});
|
|
123
|
+
return typeof text === 'string' && text ? text : (pending?.text ?? '');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function terminalCardText(cardText, outcome, resolvedText) {
|
|
127
|
+
const label = TERMINAL_LABEL[outcome]
|
|
128
|
+
? t(TERMINAL_LABEL[outcome])
|
|
129
|
+
: (typeof resolvedText === 'string' ? resolvedText : '');
|
|
130
|
+
return label ? `${cardText}\n\n${label}` : cardText;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Telegram adapter for the shared approval queue. One instance lives per bridge
|
|
135
|
+
* and owns the nonce registry, so stale cards from earlier turns are recognisable
|
|
136
|
+
* and a new approval in the same conversation supersedes the old keyboard.
|
|
137
|
+
*/
|
|
138
|
+
export class TelegramApprovalCard {
|
|
139
|
+
#registry;
|
|
140
|
+
#logger;
|
|
141
|
+
#notices;
|
|
142
|
+
|
|
143
|
+
constructor({
|
|
144
|
+
logger = console,
|
|
145
|
+
registry,
|
|
146
|
+
stateTexts = {},
|
|
147
|
+
ttlMs = 65 * 60_000,
|
|
148
|
+
} = {}) {
|
|
149
|
+
this.#registry = registry instanceof ActionCardRegistry
|
|
150
|
+
? registry
|
|
151
|
+
: new ActionCardRegistry({ ttlMs });
|
|
152
|
+
this.#logger = logger;
|
|
153
|
+
this.#notices = {
|
|
154
|
+
...DEFAULT_STATE_TEXT_OVERRIDES,
|
|
155
|
+
...stateTexts,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
get registry() {
|
|
160
|
+
return this.#registry;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Build the `render` / `onResolved` / `send` context handed to
|
|
165
|
+
* HarnessApprovalQueue. Returns an empty object when the bot cannot carry a
|
|
166
|
+
* keyboard, leaving the queue's plain-text flow completely untouched.
|
|
167
|
+
*/
|
|
168
|
+
createContext({ key, actor, target, send, bot } = {}) {
|
|
169
|
+
if (typeof bot?.sendInteractionCard !== 'function'
|
|
170
|
+
|| typeof bot?.editInteractionCard !== 'function') {
|
|
171
|
+
return {};
|
|
172
|
+
}
|
|
173
|
+
const rawSend = typeof send === 'function' ? send : async () => {};
|
|
174
|
+
let card = null;
|
|
175
|
+
// Nonce of the card being rendered, known before its message id is.
|
|
176
|
+
let cardNonce = null;
|
|
177
|
+
// A decision can land while `sendInteractionCard` is still in flight: the
|
|
178
|
+
// buttons are visible but `card` (and therefore the message id) is not set
|
|
179
|
+
// yet. Store the outcome so the terminal state is applied the moment the id
|
|
180
|
+
// arrives instead of silently leaving a live keyboard behind.
|
|
181
|
+
let pendingResolution = null;
|
|
182
|
+
// The queue sends the terminal receipt as a separate text right after
|
|
183
|
+
// `onResolved`; when the card edit already delivered it, that copy is noise.
|
|
184
|
+
let swallowResolvedText = null;
|
|
185
|
+
|
|
186
|
+
const guardedSend = async (text) => {
|
|
187
|
+
if (swallowResolvedText !== null && text === swallowResolvedText) {
|
|
188
|
+
swallowResolvedText = null;
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
return rawSend(text);
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Replace the card body with the receipt and clear its keyboard.
|
|
196
|
+
* Returns true only when the chat already shows the receipt.
|
|
197
|
+
*/
|
|
198
|
+
const applyTerminalState = async (settledCard, resolvedText, outcome) => {
|
|
199
|
+
if (settledCard.messageId === null) return false;
|
|
200
|
+
try {
|
|
201
|
+
await bot.editInteractionCard(target, settledCard.messageId, {
|
|
202
|
+
text: terminalCardText(settledCard.text, outcome, resolvedText),
|
|
203
|
+
markup: EMPTY_KEYBOARD,
|
|
204
|
+
});
|
|
205
|
+
return true;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
this.#logger.warn?.(
|
|
208
|
+
'[dsh-im:telegram] could not update a resolved approval card; the text receipt follows:',
|
|
209
|
+
error?.message ?? error,
|
|
210
|
+
);
|
|
211
|
+
await this.#retireKeyboard(bot, target, settledCard.messageId);
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
return {
|
|
217
|
+
send: guardedSend,
|
|
218
|
+
render: async (pending) => {
|
|
219
|
+
const text = telegramApprovalCardText(pending);
|
|
220
|
+
// sendInteractionCard cannot split a body, and sendMessage rejects
|
|
221
|
+
// anything over 4096 characters. A body that big keeps the text path,
|
|
222
|
+
// which splits the same bytes instead of logging a doomed 400.
|
|
223
|
+
if (text.length > TELEGRAM_APPROVAL_CARD_MAX_CHARS) {
|
|
224
|
+
this.#logger.warn?.(
|
|
225
|
+
'[dsh-im:telegram] approval body exceeds the Telegram message limit; using the plain-text approval:',
|
|
226
|
+
`${text.length} chars`,
|
|
227
|
+
);
|
|
228
|
+
await rawSend(pending.text);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const entry = this.#registry.issue({
|
|
232
|
+
conversationKey: key,
|
|
233
|
+
kind: 'approval',
|
|
234
|
+
payload: { approvalId: pending.approvalId, actor },
|
|
235
|
+
});
|
|
236
|
+
cardNonce = entry.nonce;
|
|
237
|
+
try {
|
|
238
|
+
const sent = await bot.sendInteractionCard(target, {
|
|
239
|
+
text,
|
|
240
|
+
markup: telegramApprovalMarkup(entry.nonce),
|
|
241
|
+
});
|
|
242
|
+
card = {
|
|
243
|
+
nonce: entry.nonce,
|
|
244
|
+
approvalId: pending.approvalId,
|
|
245
|
+
messageId: sent?.providerMessageIds?.at(-1) ?? null,
|
|
246
|
+
text,
|
|
247
|
+
};
|
|
248
|
+
// The card now owns the decision guidance and the terminal receipt.
|
|
249
|
+
pending.interactiveCard = true;
|
|
250
|
+
// A decision raced the send: finish the terminal edit that
|
|
251
|
+
// `onResolved` could not do while the message id was unknown.
|
|
252
|
+
if (pendingResolution) {
|
|
253
|
+
const { resolvedText, outcome } = pendingResolution;
|
|
254
|
+
pendingResolution = null;
|
|
255
|
+
await applyTerminalState(card, resolvedText, outcome);
|
|
256
|
+
}
|
|
257
|
+
} catch (error) {
|
|
258
|
+
// A platform that refuses the keyboard must not lose the approval:
|
|
259
|
+
// clear the registration and send the exact pre-card prompt instead.
|
|
260
|
+
this.#registry.settle(entry.nonce, ACTION_CARD_STATUS.REVOKED);
|
|
261
|
+
card = null;
|
|
262
|
+
pendingResolution = null;
|
|
263
|
+
this.#logger.warn?.(
|
|
264
|
+
'[dsh-im:telegram] could not deliver an approval card; falling back to the plain-text approval:',
|
|
265
|
+
error?.message ?? error,
|
|
266
|
+
);
|
|
267
|
+
await rawSend(pending.text);
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
onResolved: async (resolvedText, outcome) => {
|
|
271
|
+
const nonce = card?.nonce ?? cardNonce;
|
|
272
|
+
if (!nonce) return false;
|
|
273
|
+
// Settle first: a press arriving while the edit is in flight must be
|
|
274
|
+
// refused instead of submitting the same decision twice.
|
|
275
|
+
this.#registry.settle(
|
|
276
|
+
nonce,
|
|
277
|
+
TERMINAL_STATUS_BY_OUTCOME[outcome] ?? ACTION_CARD_STATUS.RESOLVED,
|
|
278
|
+
);
|
|
279
|
+
if (!card) {
|
|
280
|
+
// The send response is still pending. Let the queue deliver the text
|
|
281
|
+
// receipt now — the decision must never be lost — and remember the
|
|
282
|
+
// outcome so `render` clears the buttons once the id is known.
|
|
283
|
+
pendingResolution = { resolvedText, outcome };
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
const delivered = await applyTerminalState(card, resolvedText, outcome);
|
|
287
|
+
// The edit landed (or the client already shows it): tell the queue the
|
|
288
|
+
// receipt is delivered so it skips the duplicate terminal text.
|
|
289
|
+
if (delivered) swallowResolvedText = resolvedText;
|
|
290
|
+
return delivered;
|
|
291
|
+
},
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Handle one inline-keyboard press. Returns false for payloads this card did
|
|
297
|
+
* not produce, so question cards keep using their own path.
|
|
298
|
+
*/
|
|
299
|
+
async handlePress(callback, { bot, answer, submit } = {}) {
|
|
300
|
+
const parsed = parseTelegramApprovalCallback(callback?.data);
|
|
301
|
+
if (!parsed) return false;
|
|
302
|
+
const senderId = typeof callback?.senderId === 'string' ? callback.senderId : '';
|
|
303
|
+
const entry = this.#registry.get(parsed.nonce);
|
|
304
|
+
|
|
305
|
+
// Check the actor before claiming: a stranger's press must not consume the
|
|
306
|
+
// owner's only chance to decide.
|
|
307
|
+
if (entry
|
|
308
|
+
&& (entry.status === ACTION_CARD_STATUS.ACTIVE || entry.status === ACTION_CARD_STATUS.CLAIMED)
|
|
309
|
+
&& typeof entry.payload?.actor === 'string'
|
|
310
|
+
&& entry.payload.actor !== senderId) {
|
|
311
|
+
await answer?.(t(APPROVAL_CARD_NOTICES.ownerOnly));
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Synchronous claim: whoever gets here first owns the decision; a second tap
|
|
316
|
+
// (or a second client) is told what happened without submitting again.
|
|
317
|
+
const claimed = this.#registry.claim(parsed.nonce);
|
|
318
|
+
if (claimed.status !== ACTION_CARD_STATUS.ACTIVE) {
|
|
319
|
+
await answer?.(actionCardStateText(claimed.status, this.#notices));
|
|
320
|
+
if (claimed.status !== ACTION_CARD_STATUS.CLAIMED) {
|
|
321
|
+
await this.#retireKeyboard(bot, callback?.replyTarget, callback?.providerMessageId);
|
|
322
|
+
}
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const live = claimed.entry;
|
|
327
|
+
// Acknowledge before doing anything that can fail or take time.
|
|
328
|
+
await answer?.();
|
|
329
|
+
if (typeof submit !== 'function') {
|
|
330
|
+
this.#registry.settle(parsed.nonce, ACTION_CARD_STATUS.STALE);
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
const outcome = OUTCOME_BY_DECISION[parsed.action];
|
|
334
|
+
let submitted = APPROVAL_SUBMIT_RESULT.RETRYABLE;
|
|
335
|
+
try {
|
|
336
|
+
// `detailed` distinguishes a landed decision, an in-flight decision,
|
|
337
|
+
// a retryable failure and an invalid card that must be retired.
|
|
338
|
+
submitted = await submit(live.payload?.approvalId, outcome, { actor: senderId, detailed: true });
|
|
339
|
+
} catch (error) {
|
|
340
|
+
this.#logger.warn?.(
|
|
341
|
+
'[dsh-im:telegram] failed to submit an approval card decision:',
|
|
342
|
+
error?.message ?? error,
|
|
343
|
+
);
|
|
344
|
+
submitted = APPROVAL_SUBMIT_RESULT.RETRYABLE;
|
|
345
|
+
}
|
|
346
|
+
if (submitted === APPROVAL_SUBMIT_RESULT.SUBMITTED) return true;
|
|
347
|
+
if (submitted === APPROVAL_SUBMIT_RESULT.RETRYABLE
|
|
348
|
+
|| submitted === APPROVAL_SUBMIT_RESULT.BUSY) {
|
|
349
|
+
// Keep the keyboard available after a failure or while a typed decision
|
|
350
|
+
// is in flight. The queue blocks duplicate submissions; its resolution
|
|
351
|
+
// hook retires the card on success. A later RPC failure can then be retried
|
|
352
|
+
// with this same button instead of leaving it claimed or permanently stale.
|
|
353
|
+
// The callback is already acknowledged; no second toast is needed.
|
|
354
|
+
this.#registry.releaseClaim(parsed.nonce);
|
|
355
|
+
return true;
|
|
356
|
+
}
|
|
357
|
+
// The live queue no longer has this approval (resolved elsewhere, route
|
|
358
|
+
// closed). Retire the card instead of leaving a keyboard that keeps failing.
|
|
359
|
+
this.#registry.settle(parsed.nonce, ACTION_CARD_STATUS.STALE);
|
|
360
|
+
await this.#retireKeyboard(bot, callback?.replyTarget, callback?.providerMessageId);
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async #retireKeyboard(bot, target, providerMessageId) {
|
|
365
|
+
if (typeof bot?.updateInteractionCard !== 'function') return;
|
|
366
|
+
// Card delivery hands back string ids (Bot API message ids are numbers), so
|
|
367
|
+
// normalise before validating; a string guard silently skipped every cleanup.
|
|
368
|
+
const messageId = Number(providerMessageId);
|
|
369
|
+
if (!target || !Number.isSafeInteger(messageId)) return;
|
|
370
|
+
try {
|
|
371
|
+
await bot.updateInteractionCard(target, messageId, { markup: EMPTY_KEYBOARD });
|
|
372
|
+
} catch (error) {
|
|
373
|
+
this.#logger.warn?.(
|
|
374
|
+
'[dsh-im:telegram] could not clear a stale approval keyboard:',
|
|
375
|
+
error?.message ?? error,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
@@ -590,10 +590,18 @@ export class TelegramApi {
|
|
|
590
590
|
this.#logger?.warn?.(message);
|
|
591
591
|
}
|
|
592
592
|
|
|
593
|
-
async editMessageText({ chatId, messageId, text, richMessage, signal }) {
|
|
593
|
+
async editMessageText({ chatId, messageId, text, richMessage, replyMarkup, signal }) {
|
|
594
594
|
if ((text === undefined) === (richMessage === undefined)) {
|
|
595
595
|
throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
|
|
596
596
|
}
|
|
597
|
+
// Product invariant (route map F7): a rich answer never carries an inline
|
|
598
|
+
// keyboard — cards always use regular text. The Bot API would technically
|
|
599
|
+
// accept reply_markup next to rich_message, so this guard is deliberate.
|
|
600
|
+
if (richMessage !== undefined && replyMarkup !== undefined) {
|
|
601
|
+
throw new TypeError(
|
|
602
|
+
'A rich Telegram answer never carries an inline keyboard; use regular text for cards',
|
|
603
|
+
);
|
|
604
|
+
}
|
|
597
605
|
return this.#callUnbudgeted('editMessageText', {
|
|
598
606
|
chat_id: chatId,
|
|
599
607
|
message_id: messageId,
|
|
@@ -601,6 +609,7 @@ export class TelegramApi {
|
|
|
601
609
|
text,
|
|
602
610
|
link_preview_options: { is_disabled: true },
|
|
603
611
|
}),
|
|
612
|
+
...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
|
|
604
613
|
}, { signal });
|
|
605
614
|
}
|
|
606
615
|
|