@xmanrui/dsh-im 5.5.0 → 5.7.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 +24 -8
- package/README.md +24 -8
- package/assets/sponsors/88api.jpg +0 -0
- package/lib/client.js +328 -243
- package/lib/index.js +317 -317
- package/package.json +4 -4
- package/plugin-src/client/channels/dingtalk/index.js +12 -9
- package/plugin-src/client/channels/feishu/group-settings.js +5 -5
- package/plugin-src/client/channels/feishu/index.js +33 -25
- package/plugin-src/client/channels/qq/index.js +5 -5
- package/plugin-src/client/channels/shared/token-api.js +12 -7
- package/plugin-src/client/channels/shared/token-channel.js +18 -11
- package/plugin-src/client/channels/wecom/index.js +5 -5
- package/plugin-src/client/channels/wecom-app/index.js +3 -3
- package/plugin-src/client/channels/weixin/index.js +2 -2
- package/plugin-src/client/channels/whatsapp/index.js +6 -6
- package/plugin-src/client/credential-binding.js +3 -2
- package/plugin-src/client/delivery-settings.js +12 -3
- package/plugin-src/client/ds-bot-settings.js +3 -3
- package/plugin-src/client/global-settings.js +5 -2
- package/plugin-src/client/i18n-ru.js +57 -34
- package/plugin-src/client/i18n.js +211 -124
- package/plugin-src/client/session-channel-logos.js +8 -0
- package/plugin-src/host/delivery-suggestions.mjs +2 -0
- package/plugin-src/host/update-service.mjs +44 -13
- package/scripts/verify-package.mjs +1 -1
- package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
- package/src/channels/feishu/bridge.mjs +25 -3
- package/src/channels/feishu/feishu-cards.mjs +1 -45
- package/src/channels/feishu/feishu-runtime.mjs +13 -1
- package/src/channels/feishu/slash-command-panel.mjs +2 -5
- package/src/channels/qq/markdown-reply.mjs +5 -2
- package/src/channels/qq/qq-bridge.mjs +42 -2
- package/src/channels/shared/bot-workspace-store.mjs +1 -1
- package/src/channels/shared/command-catalog.mjs +8 -5
- package/src/channels/shared/delivery-failure-log.mjs +111 -0
- package/src/channels/shared/diagnostic-details.mjs +1 -0
- package/src/channels/shared/harness-client.mjs +12 -6
- package/src/channels/shared/i18n-en/shared-b.mjs +5 -0
- package/src/channels/shared/i18n-en/shared-c.mjs +3 -0
- package/src/channels/shared/i18n-en/telegram.mjs +6 -0
- package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
- package/src/channels/shared/i18n-ru/shared-c.mjs +3 -0
- package/src/channels/shared/i18n-ru/telegram.mjs +5 -0
- package/src/channels/shared/message-failure.mjs +5 -2
- package/src/channels/shared/session-error.mjs +8 -0
- package/src/channels/shared/text-harness-bridge.mjs +201 -3
- package/src/channels/shared/workspace-command.mjs +41 -16
- package/src/channels/shared/workspace-labels.mjs +65 -0
- package/src/channels/shared/workspace-session.mjs +24 -4
- package/src/channels/slack/slack-api.mjs +21 -5
- package/src/channels/slack/slack-runtime.mjs +69 -20
- package/src/channels/telegram/telegram-api.mjs +31 -2
- package/src/channels/telegram/telegram-bridge.mjs +58 -0
- package/src/channels/telegram/telegram-runtime.mjs +85 -3
- package/src/channels/wecom/wecom-bridge.mjs +1 -0
- package/src/channels/wecom/wecom-controller.mjs +89 -1
- package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
- package/src/channels/weixin/weixin-bridge.mjs +1 -0
|
@@ -1,3 +1,11 @@
|
|
|
1
1
|
export function isSessionNotFound(code) {
|
|
2
2
|
return code === 'session-not-found' || code === 'session/not-found';
|
|
3
3
|
}
|
|
4
|
+
|
|
5
|
+
// Older Hosts report corrupt logs as generic internal errors. Only recognize
|
|
6
|
+
// storage/format signatures on Session RPCs, never arbitrary internal failures.
|
|
7
|
+
export function isSessionLogCorrupt(error) {
|
|
8
|
+
return ['internal', 'gateway/internal'].includes(error?.code)
|
|
9
|
+
&& ['session.history', 'session.prompt'].includes(error?.method)
|
|
10
|
+
&& /stored log is corrupt|stored session "[^"\n]+" is corrupt|SessionFormatError:/u.test(error?.message ?? '');
|
|
11
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BusyMessageDispatcher, canAutomaticallySteer } from './busy-message-dispatcher.mjs';
|
|
2
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
3
3
|
|
|
4
4
|
import { createDeferredDeliveryCoordinator, deferredOutcomeText } from './deferred-delivery-coordinator.mjs';
|
|
5
5
|
import { t } from './i18n.mjs';
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
captureContextEnhancementSource,
|
|
14
14
|
enhanceContextContent,
|
|
15
15
|
} from './context-enhancement.mjs';
|
|
16
|
-
import { runWorkspaceCommand } from './workspace-command.mjs';
|
|
16
|
+
import { runWorkspaceCommand, workspaceSwitchFailureText } from './workspace-command.mjs';
|
|
17
17
|
import { runCompactCommand } from './compact-command.mjs';
|
|
18
18
|
import { isClearCommand, runClearCommand } from './clear-command.mjs';
|
|
19
19
|
import { isHistoryCommand, runHistoryCommand } from './history-command.mjs';
|
|
@@ -73,8 +73,14 @@ import {
|
|
|
73
73
|
messageFailureText,
|
|
74
74
|
setLastMessageFailure,
|
|
75
75
|
} from './message-failure.mjs';
|
|
76
|
+
import { logDeliveryFailure } from './delivery-failure-log.mjs';
|
|
76
77
|
import { beginStatusReaction } from './status-reaction.mjs';
|
|
77
78
|
|
|
79
|
+
/** Cap and TTL for the in-memory workspace-picker snapshots behind button presses. */
|
|
80
|
+
const MAX_WORKSPACE_CARDS = 50;
|
|
81
|
+
const WORKSPACE_CARD_TTL_MS = 60 * 60 * 1000;
|
|
82
|
+
const WORKSPACE_CARD_NONCE_BYTES = 9;
|
|
83
|
+
|
|
78
84
|
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
|
|
79
85
|
const FILE_ONLY_COMPLETION_TEXT = '任务已完成。';
|
|
80
86
|
|
|
@@ -202,6 +208,11 @@ export class TextHarnessBridge {
|
|
|
202
208
|
#approvals;
|
|
203
209
|
#batches = new BatchInputManager();
|
|
204
210
|
#interactionCard;
|
|
211
|
+
#workspaceCard;
|
|
212
|
+
// Workspace picker snapshots by nonce: the press carries an index, not a path.
|
|
213
|
+
#workspaceCards = new Map();
|
|
214
|
+
// Conversation key → the one picker card that is still authoritative there.
|
|
215
|
+
#workspaceCardKeys = new Map();
|
|
205
216
|
#contextHooks = null;
|
|
206
217
|
// Delivery attempts per message id. A failed turn releases its `markSeen` so
|
|
207
218
|
// the next poll can retry, and this counter is what keeps that from becoming
|
|
@@ -229,6 +240,7 @@ export class TextHarnessBridge {
|
|
|
229
240
|
signal,
|
|
230
241
|
keepaliveIntervalMs = 4_000,
|
|
231
242
|
interactionCard = null,
|
|
243
|
+
workspaceCard = null,
|
|
232
244
|
contextHooks = null,
|
|
233
245
|
autoSteerSameSender = false,
|
|
234
246
|
autoSteerLimit = 0,
|
|
@@ -250,6 +262,7 @@ export class TextHarnessBridge {
|
|
|
250
262
|
this.#signal = signal;
|
|
251
263
|
this.#keepaliveIntervalMs = keepaliveIntervalMs;
|
|
252
264
|
this.#interactionCard = interactionCard ?? null;
|
|
265
|
+
this.#workspaceCard = workspaceCard ?? null;
|
|
253
266
|
// Opt-in follow-up lanes for channels whose groups run on rapid consecutive
|
|
254
267
|
// posts: fold a same sender's burst into one dispatch, and steer that
|
|
255
268
|
// sender's own mid-turn follow-ups into the in-flight turn instead of
|
|
@@ -1118,6 +1131,9 @@ export class TextHarnessBridge {
|
|
|
1118
1131
|
const workspaceCommand = !hasImages && !hasFiles
|
|
1119
1132
|
? await runWorkspaceCommand(text, this.#harness, conversationKey)
|
|
1120
1133
|
: null;
|
|
1134
|
+
if (workspaceCommand && await this.#presentWorkspaceCommand(
|
|
1135
|
+
target, workspaceCommand, conversationKey,
|
|
1136
|
+
)) return;
|
|
1121
1137
|
if (workspaceCommand) {
|
|
1122
1138
|
for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
|
|
1123
1139
|
await this.#bot.sendText(target, reply);
|
|
@@ -1274,6 +1290,7 @@ export class TextHarnessBridge {
|
|
|
1274
1290
|
// the message instead of replaying a turn the Harness may already own.
|
|
1275
1291
|
await this.#markPendingSubmitted(conversationKey, messageId);
|
|
1276
1292
|
const { sessionId, answer, artifacts = [] } = await askInWorkspaceSession({
|
|
1293
|
+
onNotice: (notice) => this.#bot.sendText(target, notice),
|
|
1277
1294
|
deferredDelivery: () => ({ coordinator: this.#deferred, target: this.#descriptor.key === 'whatsapp' ? { jid: target.jid, selfChat: target.selfChat } : target }),
|
|
1278
1295
|
harness: this.#harness,
|
|
1279
1296
|
state: this.#state,
|
|
@@ -1359,12 +1376,16 @@ export class TextHarnessBridge {
|
|
|
1359
1376
|
const answerFormat = fileOnlyCompletion ? 'plain' : 'markdown';
|
|
1360
1377
|
let textDeliveryError = null;
|
|
1361
1378
|
let textReceipt = null;
|
|
1379
|
+
// What the channel observed about the send itself; it is written to the
|
|
1380
|
+
// log together with the reference id the user is shown.
|
|
1381
|
+
let deliveryEvidence = null;
|
|
1362
1382
|
if (stream) {
|
|
1363
1383
|
try {
|
|
1364
1384
|
const result = await stream.finish(semanticStream || thinkingStream
|
|
1365
1385
|
? createTextDeliveryBlock(visibleAnswer, answerFormat)
|
|
1366
1386
|
: visibleAnswer);
|
|
1367
1387
|
streamFinished = true;
|
|
1388
|
+
deliveryEvidence = result?.deliveryEvidence ?? deliveryEvidence;
|
|
1368
1389
|
textReceipt = createDeliveryReceipt({
|
|
1369
1390
|
deliveryId: messageId,
|
|
1370
1391
|
presentation: result?.presentation
|
|
@@ -1394,6 +1415,7 @@ export class TextHarnessBridge {
|
|
|
1394
1415
|
createTextDeliveryBlock(visibleAnswer, answerFormat),
|
|
1395
1416
|
)
|
|
1396
1417
|
: await this.#bot.sendText(answerTarget, visibleAnswer);
|
|
1418
|
+
deliveryEvidence = result?.deliveryEvidence ?? deliveryEvidence;
|
|
1397
1419
|
textReceipt = createDeliveryReceipt({
|
|
1398
1420
|
deliveryId: messageId,
|
|
1399
1421
|
presentation: result?.presentation ?? `${this.#descriptor.key}-text`,
|
|
@@ -1403,6 +1425,7 @@ export class TextHarnessBridge {
|
|
|
1403
1425
|
});
|
|
1404
1426
|
} catch (error) {
|
|
1405
1427
|
textDeliveryError = channelDeliveryFailure(error);
|
|
1428
|
+
deliveryEvidence = error?.deliveryEvidence ?? deliveryEvidence;
|
|
1406
1429
|
}
|
|
1407
1430
|
}
|
|
1408
1431
|
const finalDeliveryUnknown = textReceipt?.deliveryOutcome === 'unknown';
|
|
@@ -1416,6 +1439,11 @@ export class TextHarnessBridge {
|
|
|
1416
1439
|
Object.assign(new Error('Final text delivery outcome is unknown'), { code: textReceipt.reason }),
|
|
1417
1440
|
);
|
|
1418
1441
|
}
|
|
1442
|
+
if (textDeliveryError && deliveryEvidence) {
|
|
1443
|
+
// The catch further down reports this error, and the log line must
|
|
1444
|
+
// carry the same evidence the channel recorded for the failed send.
|
|
1445
|
+
textDeliveryError.deliveryEvidence = deliveryEvidence;
|
|
1446
|
+
}
|
|
1419
1447
|
// A failed final text must not discard an already registered result file.
|
|
1420
1448
|
// Settle the independent attachment path before surfacing the text error.
|
|
1421
1449
|
const delivery = await this.#deliverArtifacts(target, messageId, artifacts, textReceipt);
|
|
@@ -1424,7 +1452,8 @@ export class TextHarnessBridge {
|
|
|
1424
1452
|
throw textDeliveryError;
|
|
1425
1453
|
}
|
|
1426
1454
|
if (textDeliveryError && delivery.artifactSendErrors === 0) {
|
|
1427
|
-
setLastMessageFailure(this.#status, textDeliveryError);
|
|
1455
|
+
const failure = setLastMessageFailure(this.#status, textDeliveryError);
|
|
1456
|
+
logDeliveryFailure(this.#logger, this.#descriptor.key, failure, textDeliveryError.deliveryEvidence);
|
|
1428
1457
|
}
|
|
1429
1458
|
if (delivery.userVisible) {
|
|
1430
1459
|
this.#status.messagesReplied += 1;
|
|
@@ -1511,6 +1540,9 @@ export class TextHarnessBridge {
|
|
|
1511
1540
|
`[dsh-im:${this.#descriptor.key}] failed to process a message [${failure.referenceId}]:`,
|
|
1512
1541
|
messageFailureDiagnostic(error, failure),
|
|
1513
1542
|
);
|
|
1543
|
+
// One line per failed or unconfirmed delivery, carrying the same id the
|
|
1544
|
+
// user will quote back: a reference id nobody can grep is useless.
|
|
1545
|
+
logDeliveryFailure(this.#logger, this.#descriptor.key, failure, error?.deliveryEvidence);
|
|
1514
1546
|
if (await presentStreamFailure(failureText)) {
|
|
1515
1547
|
return error.deliveryReceipt;
|
|
1516
1548
|
}
|
|
@@ -1804,6 +1836,10 @@ export class TextHarnessBridge {
|
|
|
1804
1836
|
if (!conversationId || !senderId || !messageId || callback?.senderIsBot === true) return;
|
|
1805
1837
|
const kind = callback.kind === 'group' ? 'group' : 'direct';
|
|
1806
1838
|
const key = `${kind}:${conversationId}`;
|
|
1839
|
+
// Workspace pickers are stateless cards, not pending questions: route their
|
|
1840
|
+
// namespace before the question bookkeeping so a press can never touch it.
|
|
1841
|
+
const workspacePress = this.#workspaceCard?.parse?.(callback.data) ?? null;
|
|
1842
|
+
if (workspacePress) return this.#handleWorkspaceCardPress(callback, key, workspacePress);
|
|
1807
1843
|
const pending = this.#pendingInteractions.get(key);
|
|
1808
1844
|
const notice = (text) => this.#answerInteractionCallback(callback, text);
|
|
1809
1845
|
if (!pending) return notice(t('该问题已处理,无需再次选择。'));
|
|
@@ -1871,6 +1907,168 @@ export class TextHarnessBridge {
|
|
|
1871
1907
|
});
|
|
1872
1908
|
}
|
|
1873
1909
|
|
|
1910
|
+
/**
|
|
1911
|
+
* Send the merged /ws listing as an interactive picker when the channel and
|
|
1912
|
+
* the payload support one. Returns false so the caller can fall back to the
|
|
1913
|
+
* text list: a failed or impossible card must never lose the listing.
|
|
1914
|
+
*/
|
|
1915
|
+
async #presentWorkspaceCommand(target, command, conversationKey) {
|
|
1916
|
+
const listing = command?.listing;
|
|
1917
|
+
if (!listing
|
|
1918
|
+
|| typeof this.#workspaceCard?.render !== 'function'
|
|
1919
|
+
|| typeof this.#bot.sendInteractionCard !== 'function') return false;
|
|
1920
|
+
const nonce = randomBytes(WORKSPACE_CARD_NONCE_BYTES).toString('base64url');
|
|
1921
|
+
const card = this.#workspaceCard.render(listing, { nonce });
|
|
1922
|
+
if (!card) return false;
|
|
1923
|
+
const entry = { listing, key: conversationKey, target, createdAt: Date.now(), submitting: false };
|
|
1924
|
+
this.#rememberWorkspaceCard(nonce, entry);
|
|
1925
|
+
try {
|
|
1926
|
+
const sent = await this.#bot.sendInteractionCard(target, card);
|
|
1927
|
+
entry.messageId = Array.isArray(sent?.providerMessageIds) && sent.providerMessageIds.length > 0
|
|
1928
|
+
? String(sent.providerMessageIds[0])
|
|
1929
|
+
: undefined;
|
|
1930
|
+
await this.#activateWorkspaceCard(conversationKey, nonce);
|
|
1931
|
+
return true;
|
|
1932
|
+
} catch (error) {
|
|
1933
|
+
this.#workspaceCards.delete(nonce);
|
|
1934
|
+
this.#logger.warn?.(
|
|
1935
|
+
`[dsh-im:${this.#descriptor.key}] unable to send the workspace picker; `
|
|
1936
|
+
+ 'falling back to the text list:',
|
|
1937
|
+
error?.message ?? error,
|
|
1938
|
+
);
|
|
1939
|
+
return false;
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
/**
|
|
1944
|
+
* Only one picker stays authoritative per conversation. The previous card's
|
|
1945
|
+
* keyboard is retired as soon as its replacement exists, so an old "current"
|
|
1946
|
+
* marker can never be pressed after a newer list is on screen.
|
|
1947
|
+
*/
|
|
1948
|
+
async #activateWorkspaceCard(conversationKey, nonce) {
|
|
1949
|
+
const previousNonce = this.#workspaceCardKeys.get(conversationKey);
|
|
1950
|
+
this.#workspaceCardKeys.set(conversationKey, nonce);
|
|
1951
|
+
if (!previousNonce || previousNonce === nonce) return;
|
|
1952
|
+
const previous = this.#workspaceCards.get(previousNonce);
|
|
1953
|
+
this.#workspaceCards.delete(previousNonce);
|
|
1954
|
+
if (!previous?.messageId) return;
|
|
1955
|
+
await this.#retireCardKeyboard(previous.target, previous.messageId, previousNonce);
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
/** Drop a card's keyboard in place; failures are diagnostics, never user-facing. */
|
|
1959
|
+
async #retireCardKeyboard(target, messageId, nonce) {
|
|
1960
|
+
if (!target || !messageId || typeof this.#bot.updateInteractionCard !== 'function') return;
|
|
1961
|
+
try {
|
|
1962
|
+
await this.#bot.updateInteractionCard(target, String(messageId), {
|
|
1963
|
+
markup: { inline_keyboard: [] },
|
|
1964
|
+
});
|
|
1965
|
+
} catch (error) {
|
|
1966
|
+
// "message is not modified" and "message to edit not found" are both fine here.
|
|
1967
|
+
this.#logger.warn?.(
|
|
1968
|
+
`[dsh-im:${this.#descriptor.key}] unable to retire a workspace picker${nonce ? ` (${nonce})` : ''}:`,
|
|
1969
|
+
error?.message ?? error,
|
|
1970
|
+
);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
#rememberWorkspaceCard(nonce, entry) {
|
|
1975
|
+
const now = Date.now();
|
|
1976
|
+
for (const [key, stored] of this.#workspaceCards) {
|
|
1977
|
+
if (now - stored.createdAt > WORKSPACE_CARD_TTL_MS) this.#workspaceCards.delete(key);
|
|
1978
|
+
}
|
|
1979
|
+
// Keep the caller's object identity: it is the same entry whose messageId is
|
|
1980
|
+
// filled in once the Bot API answers, and retirement reads it from here.
|
|
1981
|
+
this.#workspaceCards.set(nonce, entry);
|
|
1982
|
+
while (this.#workspaceCards.size > MAX_WORKSPACE_CARDS) {
|
|
1983
|
+
const oldest = this.#workspaceCards.keys().next().value;
|
|
1984
|
+
if (oldest === undefined) break;
|
|
1985
|
+
this.#workspaceCards.delete(oldest);
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
/** Answer a workspace press through the current card snapshot. */
|
|
1990
|
+
async #handleWorkspaceCardPress(callback, key, press) {
|
|
1991
|
+
if (this.#signal?.aborted) return;
|
|
1992
|
+
const notice = (text) => this.#answerInteractionCallback(callback, text);
|
|
1993
|
+
const expired = t('这个列表已过期,请重新发送 /ws。');
|
|
1994
|
+
const entry = this.#workspaceCards.get(press.nonce);
|
|
1995
|
+
if (!entry || entry.key !== key || Date.now() - entry.createdAt > WORKSPACE_CARD_TTL_MS) {
|
|
1996
|
+
// A card this bridge can still identify gets its dead keyboard removed so
|
|
1997
|
+
// the same press is not offered again; an unrecognized card is only toasted
|
|
1998
|
+
// because editing an id we never issued is not a safe assumption.
|
|
1999
|
+
if (entry && entry.key === key) {
|
|
2000
|
+
this.#workspaceCards.delete(press.nonce);
|
|
2001
|
+
if (this.#workspaceCardKeys.get(key) === press.nonce) this.#workspaceCardKeys.delete(key);
|
|
2002
|
+
await this.#retireCardKeyboard(
|
|
2003
|
+
callback.replyTarget ?? entry.target,
|
|
2004
|
+
String(callback.providerMessageId),
|
|
2005
|
+
press.nonce,
|
|
2006
|
+
);
|
|
2007
|
+
}
|
|
2008
|
+
return notice(expired);
|
|
2009
|
+
}
|
|
2010
|
+
const kind = callback.kind === 'group' ? 'group' : 'direct';
|
|
2011
|
+
// The card is a command surface: the same command-permission gate as typing
|
|
2012
|
+
// the command applies to a press, otherwise a keyboard could bypass it.
|
|
2013
|
+
const decision = evaluateInboundAccess(this.#accessPolicy, {
|
|
2014
|
+
conversationType: kind,
|
|
2015
|
+
senderIds: [cleanText(callback.senderId)].filter(Boolean),
|
|
2016
|
+
isCommand: true,
|
|
2017
|
+
});
|
|
2018
|
+
if (!decision.allowed) return notice(t(COMMAND_PERMISSION_DENIED_MESSAGE));
|
|
2019
|
+
const path = entry.listing?.paths?.[press.index];
|
|
2020
|
+
if (typeof path !== 'string') return notice(expired);
|
|
2021
|
+
// Claim synchronously, before the first await: a second press arriving
|
|
2022
|
+
// while the switch is in flight must not switch a second time.
|
|
2023
|
+
if (entry.submitting) return notice(t('正在切换工作区,请稍候。'));
|
|
2024
|
+
// Idempotency follows the live authoritative current, not the snapshot: a
|
|
2025
|
+
// typed /ws or another card may have switched since this one was sent.
|
|
2026
|
+
let liveCurrent = null;
|
|
2027
|
+
try {
|
|
2028
|
+
if (typeof this.#harness.currentWorkspace === 'function') {
|
|
2029
|
+
liveCurrent = this.#harness.currentWorkspace();
|
|
2030
|
+
}
|
|
2031
|
+
} catch {
|
|
2032
|
+
// A failed read only loses the pre-check; the switch below still reports.
|
|
2033
|
+
}
|
|
2034
|
+
// The card's current marker is only a display snapshot; it cannot prove
|
|
2035
|
+
// that another command or conversation has not changed the bot workspace.
|
|
2036
|
+
if (path === liveCurrent) {
|
|
2037
|
+
return notice(t('已经在工作区:{workspace}', { workspace: path }));
|
|
2038
|
+
}
|
|
2039
|
+
entry.submitting = true;
|
|
2040
|
+
try {
|
|
2041
|
+
const switched = await this.#harness.switchWorkspace(path);
|
|
2042
|
+
const current = typeof switched === 'string' && switched ? switched : path;
|
|
2043
|
+
// Keep the snapshot truthful: the next press compares against this value.
|
|
2044
|
+
entry.listing = { ...entry.listing, current };
|
|
2045
|
+
const card = this.#workspaceCard.render(entry.listing, { nonce: press.nonce });
|
|
2046
|
+
if (card && typeof this.#bot.updateInteractionCard === 'function') {
|
|
2047
|
+
try {
|
|
2048
|
+
await this.#bot.updateInteractionCard(
|
|
2049
|
+
callback.replyTarget ?? entry.target,
|
|
2050
|
+
String(callback.providerMessageId),
|
|
2051
|
+
{ markup: card.markup },
|
|
2052
|
+
);
|
|
2053
|
+
} catch (error) {
|
|
2054
|
+
this.#logger.warn?.(
|
|
2055
|
+
`[dsh-im:${this.#descriptor.key}] unable to re-mark the workspace picker:`,
|
|
2056
|
+
error?.message ?? error,
|
|
2057
|
+
);
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
return await notice(t('工作区已切换为:{workspace}', { workspace: current }));
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
// Same classification as the typed command, so a card press and /ws N
|
|
2063
|
+
// cannot word the same failure differently.
|
|
2064
|
+
return notice(
|
|
2065
|
+
workspaceSwitchFailureText(error) ?? t('暂时无法切换工作区,请稍后重试。'),
|
|
2066
|
+
);
|
|
2067
|
+
} finally {
|
|
2068
|
+
entry.submitting = false;
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
|
|
1874
2072
|
async presentSessionSyncApproval(interaction, context, options = {}) {
|
|
1875
2073
|
return this.#approvals.handleSessionSyncRequested(interaction, context, {
|
|
1876
2074
|
...options, runtimeSignal: this.#signal ?? options.runtimeSignal, accessPolicy: this.#accessPolicy,
|
|
@@ -26,8 +26,8 @@ const SESSION_LIST_USAGE = [
|
|
|
26
26
|
'不带工作区参数时,默认列出当前对话的有效工作区(未设置对话专属工作区时即 bot 默认工作区)。',
|
|
27
27
|
].join('\n');
|
|
28
28
|
|
|
29
|
-
function commandResult(message, messages = [message]) {
|
|
30
|
-
return { handled: true, message, messages };
|
|
29
|
+
function commandResult(message, messages = [message], extra = {}) {
|
|
30
|
+
return { handled: true, message, messages, ...extra };
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
function normalizedWorkspacePath(value) {
|
|
@@ -156,13 +156,18 @@ export function splitWorkspaceCommandMessage(message) {
|
|
|
156
156
|
return messages;
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
/**
|
|
160
|
+
* The shared listing behind /ws, /workspace, /wsl, /workspaces and
|
|
161
|
+
* /workspacelist. Text stays byte-compatible with the pre-merge list so a
|
|
162
|
+
* channel without an interactive picker keeps exactly what it always showed;
|
|
163
|
+
* `listing` is the machine-readable half a channel may render as a picker.
|
|
164
|
+
*/
|
|
165
|
+
async function workspaceListingCommand(harness) {
|
|
161
166
|
if (typeof harness?.listWorkspaces !== 'function') {
|
|
162
167
|
return commandResult(t('当前机器人暂不支持列出工作区。'));
|
|
163
168
|
}
|
|
164
169
|
try {
|
|
165
|
-
const { current, paths } = await workspacePathSnapshot(harness);
|
|
170
|
+
const { current, paths, titles } = await workspacePathSnapshot(harness, { includeTitles: true });
|
|
166
171
|
if (paths.length === 0) {
|
|
167
172
|
return commandResult(t('当前 Harness Host 上没有仍然存在的已登记工作区。'));
|
|
168
173
|
}
|
|
@@ -178,7 +183,9 @@ async function runWorkspaceListCommand(match, harness) {
|
|
|
178
183
|
t('不带工作区参数时,/sessionlist 默认列出当前对话的有效工作区。'),
|
|
179
184
|
];
|
|
180
185
|
const message = lines.join('\n');
|
|
181
|
-
return commandResult(message, splitWorkspaceCommandMessage(message)
|
|
186
|
+
return commandResult(message, splitWorkspaceCommandMessage(message), {
|
|
187
|
+
listing: { current: current ?? null, paths, titles: titles ?? {} },
|
|
188
|
+
});
|
|
182
189
|
} catch (error) {
|
|
183
190
|
if (error?.code === 'workspace-bot-not-found') {
|
|
184
191
|
return commandResult(t('机器人正在移除或已重新接入,无法列出原会话的工作区。'));
|
|
@@ -187,6 +194,11 @@ async function runWorkspaceListCommand(match, harness) {
|
|
|
187
194
|
}
|
|
188
195
|
}
|
|
189
196
|
|
|
197
|
+
async function runWorkspaceListCommand(match, harness) {
|
|
198
|
+
if (match[1]?.trim()) return commandResult(t('用法:/workspacelist'));
|
|
199
|
+
return workspaceListingCommand(harness);
|
|
200
|
+
}
|
|
201
|
+
|
|
190
202
|
async function conversationEffectiveWorkspace(harness, conversationKey) {
|
|
191
203
|
if (typeof harness?.currentConversationWorkspace !== 'function'
|
|
192
204
|
|| typeof conversationKey !== 'string' || !conversationKey) return null;
|
|
@@ -484,6 +496,24 @@ async function runConversationWorkspaceCommand(command, harness, conversationKey
|
|
|
484
496
|
}
|
|
485
497
|
}
|
|
486
498
|
|
|
499
|
+
/**
|
|
500
|
+
* One failure mapping for every workspace-switch surface. The text command and
|
|
501
|
+
* the Telegram picker card call the same switch, so their receipts must not
|
|
502
|
+
* drift; returns null for errors this layer deliberately does not classify
|
|
503
|
+
* (the caller decides whether to rethrow or degrade).
|
|
504
|
+
*/
|
|
505
|
+
export function workspaceSwitchFailureText(error) {
|
|
506
|
+
if (['workspace-not-absolute', 'workspace-not-found', 'workspace-not-directory']
|
|
507
|
+
.includes(error?.code)) {
|
|
508
|
+
return t(`{message}
|
|
509
|
+
用法:/workspace 工作区序号或绝对路径`, { message: error.message });
|
|
510
|
+
}
|
|
511
|
+
if (error?.code === 'workspace-bot-not-found') {
|
|
512
|
+
return t('机器人正在移除或已重新接入,无法切换原会话的工作区。');
|
|
513
|
+
}
|
|
514
|
+
return null;
|
|
515
|
+
}
|
|
516
|
+
|
|
487
517
|
export async function runWorkspaceCommand(text, harness, conversationKey) {
|
|
488
518
|
if (!isWorkspaceCommand(text)) return null;
|
|
489
519
|
const command = text.trim();
|
|
@@ -501,9 +531,9 @@ export async function runWorkspaceCommand(text, harness, conversationKey) {
|
|
|
501
531
|
const match = WORKSPACE_COMMAND.exec(command);
|
|
502
532
|
if (!match) return null;
|
|
503
533
|
const workspace = match[1]?.trim();
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
534
|
+
// Merged command: no argument opens the same listing as /wsl, so a channel
|
|
535
|
+
// with an inline keyboard can make the list itself the switcher.
|
|
536
|
+
if (!workspace) return workspaceListingCommand(harness);
|
|
507
537
|
if (typeof harness?.switchWorkspace !== 'function') {
|
|
508
538
|
return commandResult(t('当前机器人暂不支持切换工作区。'));
|
|
509
539
|
}
|
|
@@ -523,13 +553,8 @@ export async function runWorkspaceCommand(text, harness, conversationKey) {
|
|
|
523
553
|
const current = await harness.switchWorkspace(selected);
|
|
524
554
|
return commandResult(t('工作区已切换为:{workspace}', { workspace: current }));
|
|
525
555
|
} catch (error) {
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
用法:/workspace 工作区序号或绝对路径`, { message: error.message }));
|
|
529
|
-
}
|
|
530
|
-
if (error?.code === 'workspace-bot-not-found') {
|
|
531
|
-
return commandResult(t('机器人正在移除或已重新接入,无法切换原会话的工作区。'));
|
|
532
|
-
}
|
|
556
|
+
const failure = workspaceSwitchFailureText(error);
|
|
557
|
+
if (failure) return commandResult(failure);
|
|
533
558
|
throw error;
|
|
534
559
|
}
|
|
535
560
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared display labels for workspace pickers.
|
|
3
|
+
*
|
|
4
|
+
* Paths and their snapshot order stay the callback identity; only the visible
|
|
5
|
+
* text is derived here. Every channel that offers a workspace selector (Feishu
|
|
6
|
+
* cards, Telegram inline keyboards, …) must use the same rules so the same
|
|
7
|
+
* workspace reads the same way everywhere:
|
|
8
|
+
*
|
|
9
|
+
* - a usable title wins, otherwise the folder name
|
|
10
|
+
* - colliding labels grow a parent-folder suffix until unique or rooted
|
|
11
|
+
* - overlong labels keep the head and tail with an ellipsis in the middle
|
|
12
|
+
*
|
|
13
|
+
* The rules originate from the Feishu workspace-list card (issue #300).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { posix, win32 } from 'node:path';
|
|
17
|
+
|
|
18
|
+
const WORKSPACE_LABEL_LENGTH = 22;
|
|
19
|
+
|
|
20
|
+
function cleanLabelText(value) {
|
|
21
|
+
return String(value ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
|
|
22
|
+
.replace(/\s+/gu, ' ').trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Display labels only: paths and their snapshot order remain the callback identity. */
|
|
26
|
+
export function workspaceLabels(paths, titles = {}) {
|
|
27
|
+
const entries = paths.map((path) => {
|
|
28
|
+
const api = /^[a-z]:[\\/]|^\\\\/iu.test(path) ? win32 : posix;
|
|
29
|
+
const normalized = api.normalize(path);
|
|
30
|
+
const name = cleanLabelText(api.basename(normalized) || api.parse(normalized).root);
|
|
31
|
+
const base = (typeof titles[path] === 'string' && cleanLabelText(titles[path])) || name;
|
|
32
|
+
return {
|
|
33
|
+
api, base, label: base, parent: api.dirname(normalized),
|
|
34
|
+
context: base === name ? '' : api.basename(normalized),
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
const counts = () => {
|
|
38
|
+
const result = new Map();
|
|
39
|
+
for (const { label } of entries) result.set(label, (result.get(label) ?? 0) + 1);
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
// Grow only ambiguous path suffixes; stop at the root even if display text collides.
|
|
43
|
+
for (;;) {
|
|
44
|
+
const repeated = counts();
|
|
45
|
+
let changed = false;
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
if (repeated.get(entry.label) < 2 || entry.parent === null) continue;
|
|
48
|
+
const { api, parent } = entry;
|
|
49
|
+
entry.context = api.join(api.basename(parent) || parent, entry.context);
|
|
50
|
+
entry.label = `${entry.base} · ${cleanLabelText(entry.context)}`;
|
|
51
|
+
const next = api.dirname(parent);
|
|
52
|
+
entry.parent = next === parent ? null : next;
|
|
53
|
+
changed = true;
|
|
54
|
+
}
|
|
55
|
+
if (!changed) break;
|
|
56
|
+
}
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
const chars = Array.from(entry.label);
|
|
59
|
+
if (chars.length > WORKSPACE_LABEL_LENGTH) {
|
|
60
|
+
entry.label = `${chars.slice(0, 11).join('')}…${chars.slice(-10).join('')}`;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const repeated = counts();
|
|
64
|
+
return entries.map(({ label }) => ({ label, numbered: repeated.get(label) > 1 }));
|
|
65
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { withSessionBindingLock } from './session-binding-lock.mjs';
|
|
2
2
|
import { initialSessionTitle } from './session-title.mjs';
|
|
3
|
-
import { messageDiagnosticError } from './connection-error.mjs';
|
|
3
|
+
import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
|
|
4
|
+
import { t } from './i18n.mjs';
|
|
4
5
|
|
|
5
6
|
export const WORKSPACE_SESSION_STALE = 'workspace-session-stale';
|
|
6
7
|
|
|
@@ -103,6 +104,7 @@ export async function askInWorkspaceSession({
|
|
|
103
104
|
existsOptions,
|
|
104
105
|
askOptions,
|
|
105
106
|
deferredDelivery,
|
|
107
|
+
onNotice,
|
|
106
108
|
}) {
|
|
107
109
|
const initialTitle = contextEnhanced
|
|
108
110
|
? initialSessionTitle({
|
|
@@ -114,16 +116,20 @@ export async function askInWorkspaceSession({
|
|
|
114
116
|
const renameSignal = createOptions?.signal
|
|
115
117
|
?? (typeof askOptions === 'object' ? askOptions?.signal : undefined);
|
|
116
118
|
const renameOptions = renameSignal ? { signal: renameSignal } : undefined;
|
|
119
|
+
let unreadableSessionId;
|
|
117
120
|
while (true) {
|
|
118
121
|
const diagnostic = { stage: 'session.prepare', submissionState: 'not-submitted' };
|
|
122
|
+
let dsBotSession = false;
|
|
119
123
|
try {
|
|
120
124
|
const binding = await withSessionBindingLock(state, key, async () => {
|
|
121
125
|
await awaitPendingConversationSwitch(harness, key);
|
|
122
126
|
const dsBotSessionId = await harness.resolveDsBotSession?.(key);
|
|
127
|
+
dsBotSession = Boolean(dsBotSessionId);
|
|
123
128
|
let sessionId = dsBotSessionId || state.sessionFor(key);
|
|
124
129
|
diagnostic.sessionId = sessionId;
|
|
125
130
|
let session = sessionId ? workspaceSession(harness, sessionId, key) : null;
|
|
126
|
-
|
|
131
|
+
const replacingUnreadable = sessionId && sessionId === unreadableSessionId;
|
|
132
|
+
if (!session || replacingUnreadable || !(await sessionExists(session, existsOptions))) {
|
|
127
133
|
if (dsBotSessionId) {
|
|
128
134
|
throw Object.assign(new Error('DS Bot 的当前会话不可用。'), { code: 'ds-bot-unavailable' });
|
|
129
135
|
}
|
|
@@ -153,12 +159,15 @@ export async function askInWorkspaceSession({
|
|
|
153
159
|
if (conversationGenerationMoved(harness, key, conversationGeneration)) {
|
|
154
160
|
throw workspaceSessionStaleError();
|
|
155
161
|
}
|
|
156
|
-
return { sessionId, session };
|
|
162
|
+
return { sessionId, session, recovered: replacingUnreadable };
|
|
157
163
|
}
|
|
158
164
|
return { sessionId, session };
|
|
159
165
|
});
|
|
160
166
|
if (!binding) continue;
|
|
161
167
|
diagnostic.sessionId = binding.sessionId;
|
|
168
|
+
if (binding.recovered) {
|
|
169
|
+
await onNotice?.(t('绑定会话的日志已损坏,已切换到新会话并继续处理本条消息。原会话记录已保留,历史上下文不会自动带入。'));
|
|
170
|
+
}
|
|
162
171
|
diagnostic.stage = 'prompt.prepare';
|
|
163
172
|
const artifacts = [];
|
|
164
173
|
const originalOnArtifact = typeof askOptions === 'object'
|
|
@@ -203,7 +212,18 @@ export async function askInWorkspaceSession({
|
|
|
203
212
|
...(artifacts.length > 0 ? { artifacts } : {}),
|
|
204
213
|
};
|
|
205
214
|
} catch (error) {
|
|
206
|
-
|
|
215
|
+
const failure = messageDiagnosticError(error, diagnostic);
|
|
216
|
+
// Retry once, only with positive evidence that no prompt was submitted.
|
|
217
|
+
// The binding lock rechecks identity so a concurrent /new or workspace
|
|
218
|
+
// switch cannot be overwritten by recovery of the previous Session.
|
|
219
|
+
if (!unreadableSessionId && !dsBotSession && diagnostic.sessionId
|
|
220
|
+
&& error?.code === 'session-unreadable'
|
|
221
|
+
&& !renameSignal?.aborted && !existsOptions?.signal?.aborted
|
|
222
|
+
&& extractConnectionEvidence(failure).details.submissionState === 'not-submitted') {
|
|
223
|
+
unreadableSessionId = diagnostic.sessionId;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (error?.code !== WORKSPACE_SESSION_STALE) throw failure;
|
|
207
227
|
}
|
|
208
228
|
}
|
|
209
229
|
}
|
|
@@ -155,6 +155,8 @@ function requiredString(value, name) {
|
|
|
155
155
|
return result;
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
const SLACK_MARKDOWN_TEXT_LIMIT = 12_000;
|
|
159
|
+
|
|
158
160
|
function safeOutgoingText(value, { trim = true } = {}) {
|
|
159
161
|
const raw = typeof value === 'string' ? value : '';
|
|
160
162
|
const text = trim ? raw.trim() : raw;
|
|
@@ -164,6 +166,14 @@ function safeOutgoingText(value, { trim = true } = {}) {
|
|
|
164
166
|
.replace(/<!(channel|here|everyone)(?:\^[^>]*)?>/gi, '@$1');
|
|
165
167
|
}
|
|
166
168
|
|
|
169
|
+
function markdownTextField(value) {
|
|
170
|
+
const text = safeOutgoingText(value);
|
|
171
|
+
if (text.length > SLACK_MARKDOWN_TEXT_LIMIT) {
|
|
172
|
+
throw new TypeError(`Slack markdown_text exceeds ${SLACK_MARKDOWN_TEXT_LIMIT} characters`);
|
|
173
|
+
}
|
|
174
|
+
return text;
|
|
175
|
+
}
|
|
176
|
+
|
|
167
177
|
function apiFailure(method, payload, tokenKind) {
|
|
168
178
|
const reason = cleanString(payload?.error) ?? 'unknown_error';
|
|
169
179
|
const error = new Error(`Slack ${method} failed: ${reason.replaceAll('_', ' ')}`);
|
|
@@ -272,15 +282,22 @@ export class SlackApi {
|
|
|
272
282
|
}
|
|
273
283
|
|
|
274
284
|
postMessage({ channelId, text, threadTs, signal, format = 'plain' }) {
|
|
285
|
+
const outgoing = format === 'markdown_text' ? markdownTextField(text) : safeOutgoingText(text);
|
|
286
|
+
const markdownText = format === 'markdown_text';
|
|
275
287
|
return this.#request('chat.postMessage', {
|
|
276
288
|
tokenKind: 'bot',
|
|
277
289
|
signal,
|
|
278
290
|
body: {
|
|
279
291
|
channel: slackId(channelId, 'channel id'),
|
|
280
|
-
text
|
|
281
|
-
...(
|
|
292
|
+
// markdown_text cannot be combined with text or blocks.
|
|
293
|
+
...(markdownText
|
|
294
|
+
? { markdown_text: outgoing }
|
|
295
|
+
: {
|
|
296
|
+
text: outgoing,
|
|
297
|
+
...(format === 'markdown' ? { blocks: [{ type: 'markdown', text: outgoing }] } : {}),
|
|
298
|
+
mrkdwn: format !== 'literal',
|
|
299
|
+
}),
|
|
282
300
|
...(threadTs ? { thread_ts: cleanString(threadTs) } : {}),
|
|
283
|
-
mrkdwn: true,
|
|
284
301
|
link_names: false,
|
|
285
302
|
unfurl_links: false,
|
|
286
303
|
unfurl_media: false,
|
|
@@ -295,8 +312,7 @@ export class SlackApi {
|
|
|
295
312
|
body: {
|
|
296
313
|
channel: slackId(channelId, 'channel id'),
|
|
297
314
|
ts: requiredString(ts, 'message timestamp'),
|
|
298
|
-
|
|
299
|
-
parse: 'none',
|
|
315
|
+
markdown_text: markdownTextField(text),
|
|
300
316
|
link_names: false,
|
|
301
317
|
},
|
|
302
318
|
});
|