@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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ensurePresetWorkspace } from './preset-workspaces.mjs';
|
|
1
2
|
import { t } from './i18n.mjs';
|
|
2
3
|
import { normalizeBusyMessageMode, validateBusyMessageMode } from './message-mode.mjs';
|
|
3
4
|
import { atConnectionStage, connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
|
|
@@ -12,10 +13,11 @@ import {
|
|
|
12
13
|
unlink,
|
|
13
14
|
writeFile,
|
|
14
15
|
} from 'node:fs/promises';
|
|
15
|
-
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
16
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
16
17
|
|
|
17
18
|
import {
|
|
18
19
|
normalizeAgentPresetCatalog,
|
|
20
|
+
normalizeAgentPresetId,
|
|
19
21
|
validateAgentPresetId,
|
|
20
22
|
} from './agent-preset.mjs';
|
|
21
23
|
import {
|
|
@@ -488,6 +490,7 @@ export class BotWorkspaceStore {
|
|
|
488
490
|
#path;
|
|
489
491
|
#defaultWorkspace;
|
|
490
492
|
#ungroupedWorkspace;
|
|
493
|
+
#groupByAgentPreset;
|
|
491
494
|
#version = 1;
|
|
492
495
|
#workspaces = {};
|
|
493
496
|
#agentPresets = {};
|
|
@@ -514,11 +517,12 @@ export class BotWorkspaceStore {
|
|
|
514
517
|
#writeQueue = Promise.resolve();
|
|
515
518
|
#botQueues = new Map();
|
|
516
519
|
|
|
517
|
-
constructor(path, { defaultWorkspace = defaultImWorkspace(), ungroupedWorkspace } = {}) {
|
|
520
|
+
constructor(path, { defaultWorkspace = defaultImWorkspace(), ungroupedWorkspace, groupByAgentPreset = false } = {}) {
|
|
518
521
|
if (typeof path !== 'string' || !path) throw new TypeError('workspace store path is required');
|
|
519
522
|
this.#path = path;
|
|
520
523
|
this.#defaultWorkspace = resolve(defaultWorkspace);
|
|
521
524
|
this.#ungroupedWorkspace = ungroupedWorkspace;
|
|
525
|
+
this.#groupByAgentPreset = groupByAgentPreset === true;
|
|
522
526
|
}
|
|
523
527
|
|
|
524
528
|
async load() {
|
|
@@ -719,6 +723,10 @@ export class BotWorkspaceStore {
|
|
|
719
723
|
) ?? null;
|
|
720
724
|
}
|
|
721
725
|
|
|
726
|
+
groupsByAgentPreset(botId) {
|
|
727
|
+
return this.#groupByAgentPreset && !this.conversationDirectoryFor(botId).enabled;
|
|
728
|
+
}
|
|
729
|
+
|
|
722
730
|
agentPresetFor(botId) {
|
|
723
731
|
return this.#agentPresets[botIdOf(botId)] ?? null;
|
|
724
732
|
}
|
|
@@ -1341,6 +1349,7 @@ export class BotWorkspaceStore {
|
|
|
1341
1349
|
incarnation,
|
|
1342
1350
|
expectedGeneration,
|
|
1343
1351
|
expectedConversationGeneration,
|
|
1352
|
+
preserveBotWorkspace = false,
|
|
1344
1353
|
} = {}) {
|
|
1345
1354
|
const id = botIdOf(botId);
|
|
1346
1355
|
if (typeof conversationKey !== 'string' || !conversationKey
|
|
@@ -1392,8 +1401,9 @@ export class BotWorkspaceStore {
|
|
|
1392
1401
|
// workspace switch queued while the session was being adopted must not be
|
|
1393
1402
|
// silently overwritten by the binding that started before it.
|
|
1394
1403
|
assertConversationCurrent();
|
|
1395
|
-
if (this.conversationDirectoryFor(id).enabled) {
|
|
1396
|
-
if (!
|
|
1404
|
+
if (this.conversationDirectoryFor(id).enabled || preserveBotWorkspace) {
|
|
1405
|
+
if (!preserveBotWorkspace
|
|
1406
|
+
&& !(await sameWorkspacePath(workspace, this.conversationWorkspaceFor(id, conversationKey)))) {
|
|
1397
1407
|
throw workspaceManualEditDisabled();
|
|
1398
1408
|
}
|
|
1399
1409
|
assertConversationCurrent();
|
|
@@ -2025,6 +2035,10 @@ export function createBotWorkspaceScope(
|
|
|
2025
2035
|
throw unavailableAgentPreset();
|
|
2026
2036
|
}
|
|
2027
2037
|
}
|
|
2038
|
+
if (workspaces.groupsByAgentPreset?.(botId)) {
|
|
2039
|
+
await ensurePresetWorkspace(target, workspaces.workspaceFor(botId), agentPreset, catalog, options);
|
|
2040
|
+
assertCurrentBotScope(isCurrentScope);
|
|
2041
|
+
}
|
|
2028
2042
|
await workspaces.setAgentPreset(botId, agentPreset, { incarnation });
|
|
2029
2043
|
assertCurrentBotScope(isCurrentScope);
|
|
2030
2044
|
if (catalog) {
|
|
@@ -2116,6 +2130,71 @@ export function createBotWorkspaceScope(
|
|
|
2116
2130
|
return workspaces.conversationWorkspaceFor(botId, conversationKey);
|
|
2117
2131
|
};
|
|
2118
2132
|
}
|
|
2133
|
+
if (property === 'resolveConversationWorkspace') {
|
|
2134
|
+
return async (conversationKey, options = {}) => {
|
|
2135
|
+
options.signal?.throwIfAborted();
|
|
2136
|
+
assertCurrentBotScope(isCurrentScope);
|
|
2137
|
+
const pending = pendingConversationSwitches.get(conversationKey);
|
|
2138
|
+
if (pending) await pending;
|
|
2139
|
+
await workspaces.whenBotIdle(botId);
|
|
2140
|
+
assertCurrentBotScope(isCurrentScope);
|
|
2141
|
+
const generation = workspaces.generationFor(botId);
|
|
2142
|
+
const conversationGeneration = currentConversationGeneration(conversationKey);
|
|
2143
|
+
const sessionId = scopedState.sessionFor(conversationKey);
|
|
2144
|
+
const configured = workspaces.conversationWorkspaceFor(botId, conversationKey);
|
|
2145
|
+
const preset = workspaces.agentPresetFor(botId);
|
|
2146
|
+
const assertUnchanged = () => {
|
|
2147
|
+
options.signal?.throwIfAborted();
|
|
2148
|
+
assertCurrentBotScope(isCurrentScope);
|
|
2149
|
+
if (generation !== workspaces.generationFor(botId)
|
|
2150
|
+
|| conversationGenerationIsStale(conversationKey, conversationGeneration)
|
|
2151
|
+
|| sessionId !== scopedState.sessionFor(conversationKey)
|
|
2152
|
+
|| (!sessionId && preset !== workspaces.agentPresetFor(botId))) {
|
|
2153
|
+
throw workspaceSessionStale('The conversation changed while its workspace was being resolved.');
|
|
2154
|
+
}
|
|
2155
|
+
};
|
|
2156
|
+
if (sessionId) {
|
|
2157
|
+
const known = sessionGenerations.get(sessionId)?.workspace;
|
|
2158
|
+
if (known) {
|
|
2159
|
+
assertUnchanged();
|
|
2160
|
+
return known;
|
|
2161
|
+
}
|
|
2162
|
+
// The configured bot directory stays unchanged when a preset groups
|
|
2163
|
+
// a new session. Recover its actual owner after a restart, without
|
|
2164
|
+
// adopting the session or moving an older chat to the new preset.
|
|
2165
|
+
if (typeof target.rpc === 'function') {
|
|
2166
|
+
const listed = await target.rpc('workspace.list', {}, 30_000, options);
|
|
2167
|
+
assertUnchanged();
|
|
2168
|
+
if (!Array.isArray(listed?.items)) throw new TypeError('Harness returned an invalid workspace list');
|
|
2169
|
+
const owners = listed.items.filter((item) => Array.isArray(item?.sessionIds)
|
|
2170
|
+
&& item.sessionIds.includes(sessionId));
|
|
2171
|
+
if (owners.length > 1) throw new TypeError('Harness returned multiple session workspaces');
|
|
2172
|
+
const workspace = owners[0]?.path ?? configured;
|
|
2173
|
+
if (typeof workspace !== 'string' || !isAbsolute(workspace)) {
|
|
2174
|
+
throw new TypeError('Harness returned an invalid session workspace');
|
|
2175
|
+
}
|
|
2176
|
+
sessionGenerations.set(sessionId, { ...sessionGenerations.get(sessionId), workspace });
|
|
2177
|
+
return workspace;
|
|
2178
|
+
}
|
|
2179
|
+
return configured;
|
|
2180
|
+
}
|
|
2181
|
+
// With no binding (including after /new), list the next preset's
|
|
2182
|
+
// existing group. A read never creates a directory or registers it.
|
|
2183
|
+
if (preset && workspaces.groupsByAgentPreset?.(botId)
|
|
2184
|
+
&& !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
|
|
2185
|
+
&& await target.isUngroupedWorkspace?.(configured)) {
|
|
2186
|
+
const directory = join(configured, 'presets', preset);
|
|
2187
|
+
const exists = await stat(directory).then((entry) => entry.isDirectory(), (error) => {
|
|
2188
|
+
if (error?.code === 'ENOENT') return false;
|
|
2189
|
+
throw error;
|
|
2190
|
+
});
|
|
2191
|
+
assertUnchanged();
|
|
2192
|
+
if (exists) return directory;
|
|
2193
|
+
}
|
|
2194
|
+
assertUnchanged();
|
|
2195
|
+
return configured;
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2119
2198
|
if (property === 'hasConversationWorkspaceOverride') {
|
|
2120
2199
|
return (conversationKey) => {
|
|
2121
2200
|
assertCurrentBotScope(isCurrentScope);
|
|
@@ -2240,6 +2319,17 @@ export function createBotWorkspaceScope(
|
|
|
2240
2319
|
|| adopted.sessionId !== sessionId || typeof adopted.workspace !== 'string') {
|
|
2241
2320
|
throw new TypeError('Harness returned an invalid adopted workspace session');
|
|
2242
2321
|
}
|
|
2322
|
+
// Selecting another session in the current automatic group must not
|
|
2323
|
+
// turn that group into the bot's manual directory and clear every
|
|
2324
|
+
// other conversation. Explicit cross-workspace selection keeps its
|
|
2325
|
+
// existing bot-wide semantics.
|
|
2326
|
+
const baseWorkspace = workspaces.workspaceFor(botId);
|
|
2327
|
+
const preserveBotWorkspace = !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
|
|
2328
|
+
&& normalizeAgentPresetId(basename(adopted.workspace)) !== null
|
|
2329
|
+
&& await target.isUngroupedWorkspace?.(baseWorkspace)
|
|
2330
|
+
&& await sameWorkspacePath(dirname(adopted.workspace), join(baseWorkspace, 'presets'))
|
|
2331
|
+
&& await sameWorkspacePath(adopted.workspace,
|
|
2332
|
+
await scopedHarness.resolveConversationWorkspace(conversationKey));
|
|
2243
2333
|
const bound = await workspaces.bindWorkspaceSession(botId, adopted.workspace, {
|
|
2244
2334
|
conversationKey,
|
|
2245
2335
|
sessionId,
|
|
@@ -2250,6 +2340,7 @@ export function createBotWorkspaceScope(
|
|
|
2250
2340
|
incarnation,
|
|
2251
2341
|
expectedGeneration,
|
|
2252
2342
|
expectedConversationGeneration,
|
|
2343
|
+
preserveBotWorkspace,
|
|
2253
2344
|
});
|
|
2254
2345
|
if (!isCurrentScope()) {
|
|
2255
2346
|
const error = new Error('找不到要修改的机器人。');
|
|
@@ -2304,7 +2395,13 @@ export function createBotWorkspaceScope(
|
|
|
2304
2395
|
: null;
|
|
2305
2396
|
const agentPreset = workspaces.agentPresetFor(botId);
|
|
2306
2397
|
const model = inheritBotModel === false ? null : workspaces.modelFor(botId);
|
|
2307
|
-
|
|
2398
|
+
let workspace = workspaces.conversationWorkspaceFor(botId, conversationKey);
|
|
2399
|
+
if (agentPreset && workspaces.groupsByAgentPreset?.(botId)
|
|
2400
|
+
&& !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)) {
|
|
2401
|
+
const settings = await presetSettings();
|
|
2402
|
+
workspace = await ensurePresetWorkspace(target, workspace, agentPreset, settings.agentPresetCatalog, options);
|
|
2403
|
+
assertCurrentBotScope(isCurrentScope);
|
|
2404
|
+
}
|
|
2308
2405
|
const sessionId = await target.createSession({
|
|
2309
2406
|
...createOptions,
|
|
2310
2407
|
workspace,
|
|
@@ -2418,9 +2515,23 @@ export function createBotWorkspaceScope(
|
|
|
2418
2515
|
return invokeStartedSessionMutation('renameSession', args, 'title rename');
|
|
2419
2516
|
},
|
|
2420
2517
|
} : {}),
|
|
2421
|
-
selectModel(
|
|
2422
|
-
if (dsBotId)
|
|
2423
|
-
|
|
2518
|
+
async selectModel(selection, options = {}) {
|
|
2519
|
+
if (!dsBotId) {
|
|
2520
|
+
return invokeCurrentSession('selectSessionModel', [selection, options], 'model selection');
|
|
2521
|
+
}
|
|
2522
|
+
options.signal?.throwIfAborted();
|
|
2523
|
+
if (!isCurrentSession()) throw workspaceSessionStale('DS Bot binding changed before model selection.');
|
|
2524
|
+
const bot = await dsBot?.resolve(dsBotId);
|
|
2525
|
+
options.signal?.throwIfAborted();
|
|
2526
|
+
if (!bot || bot.sessionId !== sessionId || !isCurrentSession()) {
|
|
2527
|
+
throw workspaceSessionStale('DS Bot changed before model selection.');
|
|
2528
|
+
}
|
|
2529
|
+
if (typeof dsBot.updateBotModel !== 'function') {
|
|
2530
|
+
throw deliveryTargetError('ds-bot-unavailable', 'DS Bot model selection is unavailable.');
|
|
2531
|
+
}
|
|
2532
|
+
// This is a Bot-wide setting. Never mutate only the IM session: DS
|
|
2533
|
+
// Bot applies the choice to its own and group sessions as well.
|
|
2534
|
+
return dsBot.updateBotModel(dsBotId, selection, options);
|
|
2424
2535
|
},
|
|
2425
2536
|
isRunning(...args) {
|
|
2426
2537
|
return invokeCurrentSession('isSessionRunning', args, 'run-state check');
|
|
@@ -2551,6 +2662,7 @@ export function createBotScopedHarness(harness, options) {
|
|
|
2551
2662
|
|
|
2552
2663
|
export function createWorkspaceAwareController(controller, {
|
|
2553
2664
|
workspaces,
|
|
2665
|
+
harness,
|
|
2554
2666
|
stateFor,
|
|
2555
2667
|
agentPresetCatalog,
|
|
2556
2668
|
modelCatalog,
|
|
@@ -2611,6 +2723,9 @@ export function createWorkspaceAwareController(controller, {
|
|
|
2611
2723
|
&& !catalog?.items.some((item) => item.id === normalizedAgentPreset)) {
|
|
2612
2724
|
throw unavailableAgentPreset();
|
|
2613
2725
|
}
|
|
2726
|
+
if (workspaces.groupsByAgentPreset?.(botId)) {
|
|
2727
|
+
await ensurePresetWorkspace(harness, workspaces.workspaceFor(botId), normalizedAgentPreset, catalog);
|
|
2728
|
+
}
|
|
2614
2729
|
await workspaces.setAgentPreset(botId, normalizedAgentPreset, { incarnation });
|
|
2615
2730
|
return decorateResult(
|
|
2616
2731
|
workspaces,
|
|
@@ -46,14 +46,29 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
|
|
|
46
46
|
'/conv 或 /conversation 查看当前对话工作区',
|
|
47
47
|
'/conv 工作区绝对路径或序号 设置当前对话专属工作区',
|
|
48
48
|
'/conv clear 清除专属工作区,回到 bot 默认工作区',
|
|
49
|
-
], {
|
|
49
|
+
], {
|
|
50
|
+
// Aliases stay typeable and stay in /help, but the native Telegram menu
|
|
51
|
+
// lists each command once; B16 in the command UX audit.
|
|
52
|
+
aliases: [
|
|
53
|
+
{ name: 'conversation', menuVisible: false },
|
|
54
|
+
{ name: 'thread', menuVisible: false },
|
|
55
|
+
],
|
|
56
|
+
}),
|
|
50
57
|
defineCatalogCommand('workspacelist', '列出工作区绝对路径', [
|
|
51
58
|
'/workspacelist、/wsl、/workspaces 工作区列表别名(等同 /ws)',
|
|
52
|
-
], {
|
|
59
|
+
], {
|
|
60
|
+
// Aliases stay typeable and stay in /help, but the native Telegram menu
|
|
61
|
+
// lists each command once; B16 in the command UX audit.
|
|
62
|
+
aliases: [
|
|
63
|
+
{ name: 'workspaces', menuVisible: false },
|
|
64
|
+
{ name: 'wsl', menuVisible: false },
|
|
65
|
+
],
|
|
66
|
+
menuVisible: false,
|
|
67
|
+
}),
|
|
53
68
|
defineCatalogCommand('sessionlist', '列出会话 ID 和标题', [
|
|
54
69
|
'/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
|
|
55
70
|
'/sessionlist --limit N 仅列出当前工作区前 N 个会话',
|
|
56
|
-
], { aliases: ['sessions'] }),
|
|
71
|
+
], { aliases: [{ name: 'sessions', menuVisible: false }] }),
|
|
57
72
|
defineCatalogCommand('session', '将当前聊天绑定到指定会话', [
|
|
58
73
|
'/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
|
|
59
74
|
]),
|
|
@@ -62,7 +77,7 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
|
|
|
62
77
|
]),
|
|
63
78
|
defineCatalogCommand('reasoninglist', '按序号列出当前模型可用推理等级', [
|
|
64
79
|
'/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级',
|
|
65
|
-
], { aliases: ['reasonings'] }),
|
|
80
|
+
], { aliases: [{ name: 'reasonings', menuVisible: false }] }),
|
|
66
81
|
defineCatalogCommand('reasoning', '查看或切换当前推理等级', [
|
|
67
82
|
'/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级',
|
|
68
83
|
]),
|
|
@@ -72,7 +87,7 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
|
|
|
72
87
|
]),
|
|
73
88
|
defineCatalogCommand('presetlist', '列出可用 Agent Preset', [
|
|
74
89
|
'/presetlist 或 /presets 按序号列出可用 Agent Preset',
|
|
75
|
-
], { aliases: ['presets'] }),
|
|
90
|
+
], { aliases: [{ name: 'presets', menuVisible: false }] }),
|
|
76
91
|
defineCatalogCommand('preset', '查看或设置新会话 Agent Preset', [
|
|
77
92
|
'/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset',
|
|
78
93
|
'纯数字 ID:/preset id:<ID>',
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decode a stored conversation key back into the parts a caller can reason
|
|
3
|
+
* about: whether it is a direct chat, a group, or a thread, plus the ids
|
|
4
|
+
* inside it.
|
|
5
|
+
*
|
|
6
|
+
* The keys are written by the channel codecs in `./route.mjs` (and by the
|
|
7
|
+
* channels that still own their own key shape), so this reader accepts every
|
|
8
|
+
* shape we know about. It never invents a key: an unknown or malformed string
|
|
9
|
+
* yields `null` and the caller treats the conversation as unidentified.
|
|
10
|
+
*
|
|
11
|
+
* Known shapes:
|
|
12
|
+
* direct:dm:<userId> Matrix direct chat (user ids contain `:`)
|
|
13
|
+
* direct:<id> generic direct chat; whether <id> names
|
|
14
|
+
* the peer user or the DM channel depends
|
|
15
|
+
* on the channel (see SENDER_DIRECT_CHANNELS)
|
|
16
|
+
* p2p:<userId> Feishu / Weixin / WeCom app / DingTalk
|
|
17
|
+
* c2c:<openid> QQ private chat
|
|
18
|
+
* group:<chatId> group without a thread
|
|
19
|
+
* group:<chatId>:thread:<threadId> Feishu thread (older shape)
|
|
20
|
+
* group:<chatId>:<threadId> Telegram forum topic, Slack thread
|
|
21
|
+
* group:room:<roomId>[$<root>] Matrix room, `$` separates a thread root
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @typedef {Object} ParsedConversationKey
|
|
26
|
+
* @property {'dm'|'group'|'thread'} chatType
|
|
27
|
+
* @property {?string} chatId
|
|
28
|
+
* @property {?string} threadId
|
|
29
|
+
* @property {?string} senderId
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const SEP = ':';
|
|
33
|
+
|
|
34
|
+
/** Everything before the first separator is the scope. */
|
|
35
|
+
function scopeOf(key) {
|
|
36
|
+
const index = key.indexOf(SEP);
|
|
37
|
+
return index === -1 ? key : key.slice(0, index);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function restOf(key) {
|
|
41
|
+
const index = key.indexOf(SEP);
|
|
42
|
+
return index === -1 ? '' : key.slice(index + 1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Channels whose `direct:<id>` suffix is the peer user id. Elsewhere (Slack,
|
|
47
|
+
* Discord, WhatsApp, iMessage, email, ...) it names the DM channel or chat,
|
|
48
|
+
* so reporting it as a sender would point a consumer at the wrong user.
|
|
49
|
+
*/
|
|
50
|
+
const SENDER_DIRECT_CHANNELS = new Set(['telegram', 'wecom']);
|
|
51
|
+
|
|
52
|
+
function dm(chatId, senderId) {
|
|
53
|
+
return { chatType: 'dm', chatId: chatId || null, threadId: null, senderId: senderId || null };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseDirect(rest, channel) {
|
|
57
|
+
// `direct:dm:<id>` — Matrix keeps an explicit `dm` marker; the user id
|
|
58
|
+
// itself (`@alice:example.org`) contains the separator, so take it whole.
|
|
59
|
+
if (rest.startsWith('dm' + SEP)) {
|
|
60
|
+
const id = rest.slice(3);
|
|
61
|
+
return id ? dm(null, id) : null;
|
|
62
|
+
}
|
|
63
|
+
return dm(rest, SENDER_DIRECT_CHANNELS.has(channel) ? rest : null);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `p2p:` and `c2c:` keys are written per sender by every channel that uses them. */
|
|
67
|
+
function parsePeer(rest) {
|
|
68
|
+
return dm(null, rest);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseMatrixRoom(rest) {
|
|
72
|
+
const body = rest.slice('room:'.length);
|
|
73
|
+
const mark = body.indexOf('$');
|
|
74
|
+
if (mark === -1) {
|
|
75
|
+
return body ? { chatType: 'group', chatId: body, threadId: null, senderId: null } : null;
|
|
76
|
+
}
|
|
77
|
+
const chatId = body.slice(0, mark);
|
|
78
|
+
const threadId = body.slice(mark + 1);
|
|
79
|
+
if (!chatId || !threadId) return null;
|
|
80
|
+
return { chatType: 'thread', chatId, threadId, senderId: null };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function parseGroup(rest) {
|
|
84
|
+
// Matrix rooms keep their own prefix; everything else is `<chatId>[:<thread>]`
|
|
85
|
+
// or the explicit `<chatId>:thread:<threadId>` form.
|
|
86
|
+
if (rest.startsWith('room:')) return parseMatrixRoom(rest);
|
|
87
|
+
const parts = rest.split(SEP);
|
|
88
|
+
const chatId = parts[0];
|
|
89
|
+
if (!chatId) return null;
|
|
90
|
+
if (parts.length === 1) return { chatType: 'group', chatId, threadId: null, senderId: null };
|
|
91
|
+
if (parts.length === 3 && parts[1] === 'thread' && parts[2]) {
|
|
92
|
+
return { chatType: 'thread', chatId, threadId: parts[2], senderId: null };
|
|
93
|
+
}
|
|
94
|
+
if (parts.length === 2 && parts[1]) {
|
|
95
|
+
return { chatType: 'thread', chatId, threadId: parts[1], senderId: null };
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Decode one conversation key.
|
|
102
|
+
* @param {unknown} key stored conversation key
|
|
103
|
+
* @param {{channel?: string}} [options] channel that stored the key; decides
|
|
104
|
+
* whether a `direct:<id>` suffix is a user id or a chat id
|
|
105
|
+
* @returns {?ParsedConversationKey} parts, or null when the key is not ours
|
|
106
|
+
*/
|
|
107
|
+
export function parseConversationKey(key, { channel } = {}) {
|
|
108
|
+
if (typeof key !== 'string' || key === '' || key.length > 1_024) return null;
|
|
109
|
+
const scope = scopeOf(key);
|
|
110
|
+
const rest = restOf(key);
|
|
111
|
+
if (rest === '') return null;
|
|
112
|
+
if (scope === 'direct') return parseDirect(rest, channel);
|
|
113
|
+
if (scope === 'p2p' || scope === 'c2c') return parsePeer(rest);
|
|
114
|
+
if (scope === 'group') return parseGroup(rest);
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
@@ -13,6 +13,40 @@ const EXTENSION_KEYS = Object.freeze([
|
|
|
13
13
|
|
|
14
14
|
const PENDING_MESSAGE_LIMIT = 200;
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* How many conversations remember their last author. One entry per
|
|
18
|
+
* conversation, overwritten on every inbound message, so this is a bounded
|
|
19
|
+
* map of "who spoke here last" -- never a transcript.
|
|
20
|
+
*/
|
|
21
|
+
const AUTHOR_LIMIT = 500;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Keep only what identifies the speaker: no message text, no display extras.
|
|
25
|
+
* A missing or malformed id drops the entry instead of storing a half record.
|
|
26
|
+
*/
|
|
27
|
+
function normalizeAuthor(value) {
|
|
28
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
29
|
+
const senderId = typeof value.senderId === 'string' ? value.senderId : '';
|
|
30
|
+
if (!senderId) return null;
|
|
31
|
+
const author = { senderId, isBot: value.isBot === true };
|
|
32
|
+
if (typeof value.senderName === 'string' && value.senderName) author.senderName = value.senderName;
|
|
33
|
+
if (typeof value.senderUsername === 'string' && value.senderUsername) author.senderUsername = value.senderUsername;
|
|
34
|
+
if (typeof value.at === 'string' && value.at) author.at = value.at;
|
|
35
|
+
return author;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function normalizeAuthors(value) {
|
|
39
|
+
const authors = {};
|
|
40
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return authors;
|
|
41
|
+
const keys = Object.keys(value);
|
|
42
|
+
for (const key of keys.slice(Math.max(0, keys.length - AUTHOR_LIMIT))) {
|
|
43
|
+
if (typeof key !== 'string' || !key) continue;
|
|
44
|
+
const author = normalizeAuthor(value[key]);
|
|
45
|
+
if (author) authors[key] = author;
|
|
46
|
+
}
|
|
47
|
+
return authors;
|
|
48
|
+
}
|
|
49
|
+
|
|
16
50
|
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
|
|
17
51
|
|
|
18
52
|
/**
|
|
@@ -71,9 +105,13 @@ function normalizeState(value) {
|
|
|
71
105
|
// An empty queue leaves no key behind, so an untouched state file keeps the
|
|
72
106
|
// shape earlier versions wrote.
|
|
73
107
|
const pendingMessages = normalizePendingMessages(value.pendingMessages);
|
|
108
|
+
// Authors are optional: a state file written before this field existed loads
|
|
109
|
+
// unchanged and simply reports no author.
|
|
110
|
+
const authors = normalizeAuthors(value.authors);
|
|
74
111
|
const normalized = {
|
|
75
112
|
version: 1,
|
|
76
113
|
sessions,
|
|
114
|
+
...(Object.keys(authors).length ? { authors } : {}),
|
|
77
115
|
...(pendingMessages.length ? { pendingMessages } : {}),
|
|
78
116
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
79
117
|
seenMessageIds: Array.isArray(value.seenMessageIds)
|
|
@@ -164,6 +202,30 @@ export class ConversationStateStore {
|
|
|
164
202
|
return this.#state.sessions[key] ?? null;
|
|
165
203
|
}
|
|
166
204
|
|
|
205
|
+
/** The last speaker of a conversation, or null when none was recorded. */
|
|
206
|
+
authorFor(key) {
|
|
207
|
+
const author = this.#state.authors?.[key];
|
|
208
|
+
return author ? structuredClone(author) : null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Remember who last spoke in a conversation. Persisted so the answer survives
|
|
213
|
+
* a restart; overwritten on every inbound message and bounded by AUTHOR_LIMIT.
|
|
214
|
+
*/
|
|
215
|
+
async rememberAuthor(key, value) {
|
|
216
|
+
const author = normalizeAuthor({ at: new Date().toISOString(), ...value });
|
|
217
|
+
if (typeof key !== 'string' || !key || !author) return null;
|
|
218
|
+
const authors = this.#state.authors ??= {};
|
|
219
|
+
delete authors[key];
|
|
220
|
+
authors[key] = author;
|
|
221
|
+
const keys = Object.keys(authors);
|
|
222
|
+
if (keys.length > AUTHOR_LIMIT) {
|
|
223
|
+
for (const stale of keys.slice(0, keys.length - AUTHOR_LIMIT)) delete authors[stale];
|
|
224
|
+
}
|
|
225
|
+
await this.#persist();
|
|
226
|
+
return structuredClone(author);
|
|
227
|
+
}
|
|
228
|
+
|
|
167
229
|
async setSession(key, sessionId) {
|
|
168
230
|
this.#state.sessions[key] = sessionId;
|
|
169
231
|
await this.#persist();
|
|
@@ -59,6 +59,40 @@ export const CONFIG_ISSUE_LABELS = Object.freeze({
|
|
|
59
59
|
// Map keys are replaced with zero-based positions to avoid exposing identities.
|
|
60
60
|
const CONFIG_FIELD = /^(?:\$|version|accounts(?:\[\d{1,10}\](?:\.(?:accountId|ownerUserId|botId|tokenRef|baseUrl))?)?|(?:workspaces|agentPresets|models)(?:\[\d{1,10}\]\.(?:key|value))?|deliveryTargets(?:\[\d{1,10}\]\.(?:key|targets(?:\[\d{1,10}\])?))?)$/;
|
|
61
61
|
|
|
62
|
+
// A local-library failure is often only distinguishable by its message:
|
|
63
|
+
// `QRCode.toDataURL is not a function` and `String required as first argument`
|
|
64
|
+
// are different bugs with identical error types and reasons. Free-form text is
|
|
65
|
+
// never forwarded; only messages that already look like a known local-library
|
|
66
|
+
// diagnostic are admitted, so a service error carrying a URL, a credential or a
|
|
67
|
+
// piece of user content stays out of the report entirely.
|
|
68
|
+
const DIAGNOSTIC_MESSAGE_SHAPES = [
|
|
69
|
+
// `QRCode.toDataURL is not a function`, `PNG.sync.write is not a constructor`
|
|
70
|
+
/^(?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]* is not a (?:function|constructor)$/u,
|
|
71
|
+
// node-qrcode validating its argument
|
|
72
|
+
/^String required as first argument$/u,
|
|
73
|
+
// property access on undefined inside the encoder
|
|
74
|
+
/^Cannot read propert(?:y|ies) .{1,100}$/u,
|
|
75
|
+
// zlib: `invalid stored block lengths`, `incorrect header check`, `Invalid data`
|
|
76
|
+
/^(?:invalid|incorrect|unexpected|unknown|bad)\s+[A-Za-z][A-Za-z0-9 _-]{2,80}$/iu,
|
|
77
|
+
// pngjs / buffer: `padding not multiple of block size`, `buffer write failed`
|
|
78
|
+
/^[A-Za-z][A-Za-z0-9 _-]{2,60}(?: not multiple of block size| failed)$/u,
|
|
79
|
+
];
|
|
80
|
+
const DIAGNOSTIC_MESSAGE_DENY = /(?:token|secret|password|passwd|authorization|bearer|cookie)/iu;
|
|
81
|
+
const DIAGNOSTIC_MESSAGE_URL = /\b(?:[a-z][a-z0-9+.-]*:\/\/)\S*/iu;
|
|
82
|
+
const DIAGNOSTIC_MESSAGE_EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+/u;
|
|
83
|
+
const DIAGNOSTIC_MESSAGE_OPAQUE = /\b[A-Za-z0-9_\-+/=]{32,}\b/u;
|
|
84
|
+
|
|
85
|
+
export function safeDiagnosticMessage(value) {
|
|
86
|
+
if (typeof value !== 'string') return undefined;
|
|
87
|
+
const text = value.replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();
|
|
88
|
+
if (!/^[\x20-\x7e]+$/u.test(text)) return undefined;
|
|
89
|
+
if (!DIAGNOSTIC_MESSAGE_SHAPES.some(shape => shape.test(text))) return undefined;
|
|
90
|
+
if (DIAGNOSTIC_MESSAGE_DENY.test(text)) return undefined;
|
|
91
|
+
if (DIAGNOSTIC_MESSAGE_URL.test(text) || DIAGNOSTIC_MESSAGE_EMAIL.test(text)) return undefined;
|
|
92
|
+
if (DIAGNOSTIC_MESSAGE_OPAQUE.test(text)) return undefined;
|
|
93
|
+
return text;
|
|
94
|
+
}
|
|
95
|
+
|
|
62
96
|
export function normalizeDiagnosticDetails(value) {
|
|
63
97
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
|
64
98
|
const result = {};
|
|
@@ -104,6 +138,10 @@ export function normalizeDiagnosticDetails(value) {
|
|
|
104
138
|
if (typeof value.pluginVersion === 'string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.pluginVersion)
|
|
105
139
|
&& value.pluginVersion.length <= 64) result.pluginVersion = value.pluginVersion;
|
|
106
140
|
if (['succeeded', 'failed', 'not-attempted', 'unknown'].includes(value.rollback)) result.rollback = value.rollback;
|
|
141
|
+
if (typeof value.causeMessage === 'string') {
|
|
142
|
+
const message = safeDiagnosticMessage(value.causeMessage);
|
|
143
|
+
if (message) result.causeMessage = message;
|
|
144
|
+
}
|
|
107
145
|
if (typeof value.hint === 'string' && value.hint.trim()) result.hint = value.hint.trim().slice(0, 500);
|
|
108
146
|
return result;
|
|
109
147
|
}
|