@xmanrui/dsh-im 5.10.0 → 5.11.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 +39 -5
- package/README.md +42 -5
- package/bin/dsh-im.mjs +65 -0
- package/docs/client-integration.md +4 -0
- package/lib/client.js +1202 -95
- package/lib/index.js +365 -339
- package/package.json +7 -6
- package/plugin-src/client/access-policy-settings.js +210 -12
- package/plugin-src/client/bot-general-settings.js +44 -3
- package/plugin-src/client/i18n-ru.js +85 -0
- package/plugin-src/client/i18n.js +83 -0
- package/plugin-src/client/im-channels.js +419 -0
- package/plugin-src/client/index.js +33 -1
- package/plugin-src/client/styles.js +7 -7
- package/plugin-src/client/update-panel.js +2 -1
- package/plugin-src/host/channel-list-rpc.mjs +280 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
- package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
- package/plugin-src/host/channels/feishu/production.mjs +39 -10
- package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
- package/plugin-src/host/channels/matrix/production.mjs +28 -10
- package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
- package/plugin-src/host/channels/qq/production.mjs +30 -11
- package/plugin-src/host/channels/qq/rpc.mjs +10 -1
- package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
- package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
- package/plugin-src/host/channels/shared/production.mjs +14 -1
- package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/rpc.mjs +9 -0
- package/plugin-src/host/channels/slack/production.mjs +28 -10
- package/plugin-src/host/channels/slack/rpc.mjs +10 -0
- package/plugin-src/host/channels/telegram/production.mjs +5 -0
- package/plugin-src/host/channels/wecom/production.mjs +28 -10
- package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
- package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
- package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
- package/plugin-src/host/channels/weixin/production.mjs +28 -10
- package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
- package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
- package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
- package/plugin-src/host/delivery-service.mjs +3 -4
- package/plugin-src/host/delivery-suggestions.mjs +3 -1
- package/plugin-src/host/harness-connection.mjs +2 -1
- package/plugin-src/host/harness-peer.mjs +3 -1
- package/plugin-src/host/index.mjs +8 -1
- package/plugin-src/host/modern-harness-api.mjs +5 -1
- package/plugin-src/host/root-scope.mjs +32 -0
- package/plugin-src/host/session-sync-coordinator.mjs +2 -1
- package/plugin-src/management-rpc.mjs +18 -2
- package/scripts/verify-package.mjs +36 -7
- package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
- package/src/channels/dingtalk/state-store.mjs +56 -0
- package/src/channels/discord/discord-api.mjs +2 -1
- package/src/channels/feishu/bridge.mjs +154 -58
- package/src/channels/feishu/feishu-cards.mjs +10 -4
- package/src/channels/feishu/feishu-runtime.mjs +11 -3
- package/src/channels/feishu/message-utils.mjs +106 -30
- package/src/channels/feishu/slash-command-panel.mjs +26 -0
- package/src/channels/feishu/state-store.mjs +14 -0
- package/src/channels/matrix/matrix-api.mjs +2 -1
- package/src/channels/qq/qq-bridge.mjs +105 -14
- package/src/channels/qq/state-store.mjs +13 -1
- package/src/channels/shared/access-policy.mjs +60 -7
- package/src/channels/shared/bot-workspace-store.mjs +155 -3
- package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
- package/src/channels/shared/channel-capabilities.mjs +44 -0
- package/src/channels/shared/command-catalog.mjs +68 -3
- package/src/channels/shared/command-permission.mjs +6 -2
- package/src/channels/shared/conversation-state-store.mjs +16 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
- package/src/channels/shared/deferred-delivery.mjs +4 -0
- package/src/channels/shared/diagnostic-details.mjs +6 -1
- package/src/channels/shared/failure-log-file.mjs +79 -0
- package/src/channels/shared/harness-client.mjs +111 -6
- package/src/channels/shared/i18n-en/feishu.mjs +2 -2
- package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-en/weixin.mjs +4 -0
- package/src/channels/shared/i18n-en.mjs +2 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
- package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
- package/src/channels/shared/i18n-ru.mjs +2 -0
- package/src/channels/shared/inbound-access.mjs +10 -0
- package/src/channels/shared/markdown-chunks.mjs +5 -0
- package/src/channels/shared/message-failure.mjs +22 -1
- package/src/channels/shared/new-command.mjs +158 -4
- package/src/channels/shared/plan-goal-command.mjs +132 -0
- package/src/channels/shared/qrcode.mjs +5 -0
- package/src/channels/shared/reply-content.mjs +102 -0
- package/src/channels/shared/reset-command.mjs +46 -0
- package/src/channels/shared/semantic/artifact.mjs +133 -29
- package/src/channels/shared/semantic/reply-reference.mjs +18 -3
- package/src/channels/shared/session-nav-command.mjs +999 -0
- package/src/channels/shared/session-ring-support.mjs +184 -0
- package/src/channels/shared/session-ring.mjs +202 -0
- package/src/channels/shared/session-title.mjs +11 -0
- package/src/channels/shared/status-command.mjs +2 -1
- package/src/channels/shared/text-harness-bridge.mjs +166 -7
- package/src/channels/shared/workspace-command.mjs +567 -31
- package/src/channels/shared/workspace-session.mjs +39 -3
- package/src/channels/slack/slack-api.mjs +2 -1
- package/src/channels/telegram/config-store.mjs +10 -2
- package/src/channels/telegram/telegram-rich-message.mjs +17 -5
- package/src/channels/telegram/telegram-runtime.mjs +14 -1
- package/src/channels/wecom/state-store.mjs +13 -1
- package/src/channels/wecom/wecom-bridge.mjs +183 -26
- package/src/channels/wecom-app/state-store.mjs +13 -1
- package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
- package/src/channels/weixin/state-store.mjs +13 -1
- package/src/channels/weixin/weixin-bridge.mjs +71 -4
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// Read-only management RPC for the channel directory and bound-session transcripts.
|
|
2
|
+
// Transcript reads use official sessionQuery; no archive parsing or sqlite access.
|
|
3
|
+
// The directory covers standard bot/account state plus configured Feishu legacy state.
|
|
4
|
+
// Custom dataDir/botsDir overrides are not inferred.
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
|
|
10
|
+
import { registerManagementRpc } from '../management-rpc.mjs';
|
|
11
|
+
import { LEGACY_FEISHU_SECRET_REF } from '../../src/channels/feishu/plugin-config-store.mjs';
|
|
12
|
+
|
|
13
|
+
export const CHANNEL_LIST_RPC_CHANNEL = '/dsh-im-channels';
|
|
14
|
+
const MAX_STATE_BYTES = 8 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
function dshHome(config = {}) {
|
|
17
|
+
return resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sessionRows(raw) {
|
|
21
|
+
const sessions = raw?.sessions;
|
|
22
|
+
if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) return [];
|
|
23
|
+
return Object.entries(sessions)
|
|
24
|
+
.filter(([, sessionId]) => typeof sessionId === 'string' && sessionId.length > 0)
|
|
25
|
+
.map(([key, sessionId]) => ({ key, sessionId }));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function directoryEntries(path) {
|
|
29
|
+
try {
|
|
30
|
+
return await readdir(path, { withFileTypes: true });
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function readJson(path) {
|
|
38
|
+
const info = await stat(path);
|
|
39
|
+
if (!info.isFile() || info.size > MAX_STATE_BYTES) return null;
|
|
40
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readState(path, botId) {
|
|
44
|
+
const raw = await readJson(path);
|
|
45
|
+
return sessionRows(raw).map(row => ({ ...row, botId }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function feishuLegacyBotIds(integrationRoot, warnings) {
|
|
49
|
+
let config;
|
|
50
|
+
try {
|
|
51
|
+
config = await readJson(join(integrationRoot, 'config.json'));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') {
|
|
54
|
+
warnings.push(`dsh-feishu/config.json: ${error?.message ?? error}`);
|
|
55
|
+
}
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) return [];
|
|
59
|
+
const version2 = config.version === 2 && Array.isArray(config.bots);
|
|
60
|
+
const bots = version2 ? config.bots : [config];
|
|
61
|
+
const ids = [];
|
|
62
|
+
for (const bot of bots) {
|
|
63
|
+
if (!bot || typeof bot !== 'object' || Array.isArray(bot)) continue;
|
|
64
|
+
// PluginConfigStore normalizes these fields with trim before selecting state.
|
|
65
|
+
const id = typeof bot.id === 'string' ? bot.id.trim() : '';
|
|
66
|
+
const secretRef = typeof bot.secretRef === 'string' ? bot.secretRef.trim() : '';
|
|
67
|
+
const legacy = version2
|
|
68
|
+
? secretRef === LEGACY_FEISHU_SECRET_REF
|
|
69
|
+
: !secretRef || secretRef === LEGACY_FEISHU_SECRET_REF;
|
|
70
|
+
if (!legacy) continue;
|
|
71
|
+
if (/^[A-Za-z0-9_-]{1,128}$/.test(id)) {
|
|
72
|
+
ids.push(id);
|
|
73
|
+
} else if (!version2 && typeof bot.appId === 'string' && bot.appId.trim()) {
|
|
74
|
+
// Match the v1 migration identity without loading the write-capable config store.
|
|
75
|
+
ids.push(`bot_${createHash('sha256').update(bot.appId.trim()).digest('hex').slice(0, 24)}`);
|
|
76
|
+
} else {
|
|
77
|
+
warnings.push('dsh-feishu/config.json: legacy bot has no usable id');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return [...new Set(ids)];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function buildList(config = {}) {
|
|
84
|
+
const root = dshHome(config);
|
|
85
|
+
const integrationsRoot = join(root, 'integrations');
|
|
86
|
+
const byChannel = new Map();
|
|
87
|
+
const warnings = [];
|
|
88
|
+
let scannedFiles = 0;
|
|
89
|
+
|
|
90
|
+
const integrations = await directoryEntries(integrationsRoot);
|
|
91
|
+
for (const integration of integrations) {
|
|
92
|
+
if (!integration.isDirectory() || !/^dsh-[A-Za-z0-9-]+$/.test(integration.name)) continue;
|
|
93
|
+
const channel = integration.name.slice('dsh-'.length);
|
|
94
|
+
const integrationRoot = join(integrationsRoot, integration.name);
|
|
95
|
+
const legacyBotIds = new Set(channel === 'feishu'
|
|
96
|
+
? await feishuLegacyBotIds(integrationRoot, warnings)
|
|
97
|
+
: []);
|
|
98
|
+
|
|
99
|
+
const collectState = async (statePath, botId, warningKey) => {
|
|
100
|
+
let rows;
|
|
101
|
+
try {
|
|
102
|
+
rows = await readState(statePath, botId);
|
|
103
|
+
scannedFiles += 1;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') {
|
|
106
|
+
warnings.push(`${warningKey}: ${error?.message ?? error}`);
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (rows.length === 0) return;
|
|
111
|
+
const group = byChannel.get(channel) ?? { channel, sessions: [] };
|
|
112
|
+
group.sessions.push(...rows);
|
|
113
|
+
byChannel.set(channel, group);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const container = channel === 'weixin' ? 'accounts' : 'bots';
|
|
117
|
+
const bots = await directoryEntries(join(integrationRoot, container));
|
|
118
|
+
for (const bot of bots) {
|
|
119
|
+
if (!bot.isDirectory() || legacyBotIds.has(bot.name)) continue;
|
|
120
|
+
await collectState(
|
|
121
|
+
join(integrationRoot, container, bot.name, 'state.json'),
|
|
122
|
+
bot.name,
|
|
123
|
+
`${integration.name}/${bot.name}`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
for (const botId of legacyBotIds) {
|
|
127
|
+
await collectState(
|
|
128
|
+
join(integrationRoot, 'state.json'),
|
|
129
|
+
botId,
|
|
130
|
+
`${integration.name}/${botId}/legacy-state`,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const channels = [...byChannel.values()]
|
|
136
|
+
.map(group => ({
|
|
137
|
+
...group,
|
|
138
|
+
sessions: group.sessions.sort((a, b) =>
|
|
139
|
+
a.key.localeCompare(b.key) || a.sessionId.localeCompare(b.sessionId) || a.botId.localeCompare(b.botId)),
|
|
140
|
+
}))
|
|
141
|
+
.sort((a, b) => a.channel.localeCompare(b.channel));
|
|
142
|
+
return { channels, scannedFiles, warnings };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const DEFAULT_DETAIL_LIMIT = 100;
|
|
146
|
+
const MAX_DETAIL_LIMIT = 200;
|
|
147
|
+
const MAX_MESSAGE_TEXT_CHARS = 30000;
|
|
148
|
+
const SESSION_ID_PATTERN = /^session-[A-Za-z0-9][A-Za-z0-9-]{0,127}$/;
|
|
149
|
+
|
|
150
|
+
function messageText(content) {
|
|
151
|
+
if (typeof content === 'string') return content;
|
|
152
|
+
if (!Array.isArray(content)) return '';
|
|
153
|
+
return content
|
|
154
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
155
|
+
.map(block => block.text)
|
|
156
|
+
.join('\n\n');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// A human transcript must use append-origin events, not the model-visible
|
|
160
|
+
// surface: replacement copies can shadow conversation the user already saw.
|
|
161
|
+
export function transcriptMessages(events) {
|
|
162
|
+
const messages = [];
|
|
163
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
164
|
+
if (event?.surfaceOp !== 'append') continue;
|
|
165
|
+
let role;
|
|
166
|
+
let content;
|
|
167
|
+
if (event.type === 'user/message' && event.data?.source?.kind === 'user') {
|
|
168
|
+
role = 'user';
|
|
169
|
+
content = event.data?.content;
|
|
170
|
+
} else if (event.type === 'assistant/message' && event.data?.message?.role === 'assistant') {
|
|
171
|
+
role = 'assistant';
|
|
172
|
+
content = event.data.message.content;
|
|
173
|
+
} else {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const fullText = messageText(content);
|
|
177
|
+
if (!fullText) continue;
|
|
178
|
+
messages.push({
|
|
179
|
+
id: `${event.seq}:${role}`,
|
|
180
|
+
seq: event.seq,
|
|
181
|
+
time: Number.isFinite(event.time) ? event.time : null,
|
|
182
|
+
role,
|
|
183
|
+
text: fullText.slice(0, MAX_MESSAGE_TEXT_CHARS),
|
|
184
|
+
...(fullText.length > MAX_MESSAGE_TEXT_CHARS ? { truncated: true } : {}),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return messages;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function findBinding(directory, payload) {
|
|
191
|
+
if (typeof payload?.channel !== 'string' || typeof payload?.key !== 'string'
|
|
192
|
+
|| typeof payload?.botId !== 'string'
|
|
193
|
+
|| typeof payload?.sessionId !== 'string' || !SESSION_ID_PATTERN.test(payload.sessionId)) return null;
|
|
194
|
+
for (const group of directory.channels) {
|
|
195
|
+
if (group.channel !== payload.channel) continue;
|
|
196
|
+
const row = group.sessions.find(candidate => candidate.key === payload.key
|
|
197
|
+
&& candidate.botId === payload.botId && candidate.sessionId === payload.sessionId);
|
|
198
|
+
if (row) return row;
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function detailError(code, message) {
|
|
204
|
+
return { ok: false, error: { code, message, details: {} } };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function readSessionDetail(sessionQuery, config, payload) {
|
|
208
|
+
const limit = payload.limit === undefined ? DEFAULT_DETAIL_LIMIT : payload.limit;
|
|
209
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_DETAIL_LIMIT
|
|
210
|
+
|| (payload.offset !== undefined && (!Number.isInteger(payload.offset) || payload.offset < 0))) {
|
|
211
|
+
return detailError('channel-session/invalid-request', 'limit 或 offset 参数无效');
|
|
212
|
+
}
|
|
213
|
+
// Re-scan and require the exact channel/key/sessionId binding. The RPC must
|
|
214
|
+
// not become an arbitrary session reader merely because a caller knows an id.
|
|
215
|
+
const directory = await buildList(config);
|
|
216
|
+
const binding = findBinding(directory, payload);
|
|
217
|
+
if (!binding) return detailError('channel-session/not-bound', '该会话不属于指定通道绑定,可能已解绑');
|
|
218
|
+
if (typeof sessionQuery?.readSession !== 'function') {
|
|
219
|
+
return detailError('channel-session/read-unavailable', '宿主 sessionQuery 服务尚未就绪');
|
|
220
|
+
}
|
|
221
|
+
const snapshot = await sessionQuery.readSession(payload.sessionId);
|
|
222
|
+
const allMessages = transcriptMessages(snapshot.events);
|
|
223
|
+
const total = allMessages.length;
|
|
224
|
+
const offset = payload.offset === undefined
|
|
225
|
+
? Math.max(0, total - limit)
|
|
226
|
+
: Math.min(payload.offset, total);
|
|
227
|
+
return {
|
|
228
|
+
ok: true,
|
|
229
|
+
value: {
|
|
230
|
+
channel: payload.channel,
|
|
231
|
+
key: payload.key,
|
|
232
|
+
botId: binding.botId,
|
|
233
|
+
sessionId: payload.sessionId,
|
|
234
|
+
createdAt: snapshot.session?.createdAt ?? null,
|
|
235
|
+
capturedThroughSeq: snapshot.events?.at(-1)?.seq ?? null,
|
|
236
|
+
total,
|
|
237
|
+
offset,
|
|
238
|
+
limit,
|
|
239
|
+
hasMore: offset > 0,
|
|
240
|
+
nextOffset: Math.max(0, offset - limit),
|
|
241
|
+
messages: allMessages.slice(offset, offset + limit),
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function installChannelListRpc(ctx, authority = undefined, config = {}) {
|
|
247
|
+
// Cordis throws on ctx.sessionQuery unless this fiber declared the injection.
|
|
248
|
+
// Resolve it only in the inject callback below, after the directory route exists.
|
|
249
|
+
let sessionQuery;
|
|
250
|
+
const handler = async (method, payload = {}, signal) => {
|
|
251
|
+
try {
|
|
252
|
+
if (method === 'list.channels') {
|
|
253
|
+
// connection.rpc preserves only { ok, value } on success; extra fields are dropped.
|
|
254
|
+
return { ok: true, value: await buildList(config) };
|
|
255
|
+
}
|
|
256
|
+
if (method === 'session.read') return await readSessionDetail(sessionQuery, config, payload);
|
|
257
|
+
return { ok: false, error: { code: 'channel-list/unknown-method', message: `Unknown method: ${method}` } };
|
|
258
|
+
} catch (error) {
|
|
259
|
+
return detailError(
|
|
260
|
+
method === 'session.read' ? 'channel-session/unavailable' : 'channel-list/unavailable',
|
|
261
|
+
String(error?.message ?? error),
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const stopRpc = registerManagementRpc(ctx, CHANNEL_LIST_RPC_CHANNEL, handler, { authority });
|
|
266
|
+
// Keep the directory available even if the optional query service is late;
|
|
267
|
+
// session.read then reports an explicit not-ready error instead of breaking list.channels.
|
|
268
|
+
const stopQuery = typeof ctx.inject === 'function'
|
|
269
|
+
? ctx.inject(['sessionQuery'], queryCtx => {
|
|
270
|
+
sessionQuery = queryCtx.sessionQuery;
|
|
271
|
+
return () => { sessionQuery = undefined; };
|
|
272
|
+
})
|
|
273
|
+
: null;
|
|
274
|
+
return () => {
|
|
275
|
+
if (typeof stopQuery === 'function') stopQuery();
|
|
276
|
+
else stopQuery?.dispose?.();
|
|
277
|
+
if (typeof stopRpc === 'function') stopRpc();
|
|
278
|
+
else stopRpc?.dispose?.();
|
|
279
|
+
};
|
|
280
|
+
}
|
|
@@ -19,6 +19,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
|
|
|
19
19
|
import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
|
|
20
20
|
import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
|
|
21
21
|
import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
|
|
22
|
+
import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
|
|
22
23
|
import { createConnectionSupervisor } from './connection-supervisor.mjs';
|
|
23
24
|
import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
|
|
24
25
|
import { harnessConnection } from '../../harness-connection.mjs';
|
|
@@ -82,14 +83,29 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
82
83
|
const stateStores = new Map();
|
|
83
84
|
|
|
84
85
|
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Every binding change is announced the moment it is written: a bind before the
|
|
88
|
+
* Session exists, an unbind when the conversation moves to another session or
|
|
89
|
+
* its binding is cleared. Listeners run synchronously.
|
|
90
|
+
*/
|
|
91
|
+
const announcer = createBindingAnnouncer({
|
|
92
|
+
channel: 'dingtalk',
|
|
93
|
+
emit: (event, payload) => ctx.emit(event, payload),
|
|
94
|
+
authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
|
|
95
|
+
? stateStores.get(botId).snapshot()?.authors ?? null
|
|
96
|
+
: null),
|
|
97
|
+
});
|
|
98
|
+
const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
|
|
99
|
+
announcer,
|
|
100
|
+
StateStore,
|
|
101
|
+
statePath,
|
|
102
|
+
states: stateStores,
|
|
103
|
+
logger,
|
|
104
|
+
});
|
|
105
|
+
// Warm the per-bot state memo now: the synchronous identity lookup can only
|
|
106
|
+
// answer from state that is already loaded in this process, and the first prompt
|
|
107
|
+
// of a session arrives long before any delivery call would load it.
|
|
108
|
+
await prime(configuredBots.map((bot) => bot.botId));
|
|
93
109
|
const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
|
|
94
110
|
const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
|
|
95
111
|
const inboundTtlService = inboundTtl?.service ?? inboundTtl;
|
|
@@ -153,8 +169,8 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
153
169
|
});
|
|
154
170
|
},
|
|
155
171
|
deleteState: async ({ botId }) => {
|
|
156
|
-
const state =
|
|
157
|
-
|
|
172
|
+
const state = stateForSync(botId);
|
|
173
|
+
forget(botId);
|
|
158
174
|
if (state && typeof state.remove === 'function') {
|
|
159
175
|
await state.remove();
|
|
160
176
|
} else {
|
|
@@ -184,6 +200,8 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
184
200
|
controller,
|
|
185
201
|
deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
|
|
186
202
|
channel: 'dingtalk', workspaces, coreController, stateFor,
|
|
203
|
+
// The same store, without the await: it is a memo of already loaded bots.
|
|
204
|
+
stateForSync,
|
|
187
205
|
}),
|
|
188
206
|
ready: supervisor.ready,
|
|
189
207
|
async close() {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../src/channels/shared/message-mode.mjs';
|
|
2
|
+
import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
|
|
2
3
|
import { diagnosticFields } from '../../../../src/channels/shared/diagnostic-details.mjs';
|
|
3
4
|
import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../src/channels/shared/connection-error.mjs';
|
|
4
5
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
5
6
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
6
|
-
import QRCode from 'qrcode';
|
|
7
|
+
import QRCode from '../../../../src/channels/shared/qrcode.mjs';
|
|
7
8
|
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
8
9
|
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
|
|
9
10
|
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
|
|
@@ -30,6 +31,7 @@ export const DINGTALK_ENDPOINTS = Object.freeze({
|
|
|
30
31
|
setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
|
|
31
32
|
setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
|
|
32
33
|
setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
|
|
34
|
+
setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
|
|
33
35
|
setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
|
|
34
36
|
setAlias: SET_ALIAS_ENDPOINT,
|
|
35
37
|
approveSender: 'bot.sender.approve',
|
|
@@ -111,6 +113,10 @@ function payloadFailure(endpoint, payload) {
|
|
|
111
113
|
return validAgentPresetPayload(payload)
|
|
112
114
|
? null : '请选择 Agent Preset。';
|
|
113
115
|
}
|
|
116
|
+
if (endpoint === DINGTALK_ENDPOINTS.setReplyContent) {
|
|
117
|
+
return validReplyContentPayload(payload)
|
|
118
|
+
? null : '请选择要投递的回复内容。';
|
|
119
|
+
}
|
|
114
120
|
if (endpoint === DINGTALK_ENDPOINTS.setBusyMessageMode) {
|
|
115
121
|
return validMessageModePayload(payload)
|
|
116
122
|
? null : '请提交有效的消息处理方式。';
|
|
@@ -315,6 +321,9 @@ export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } =
|
|
|
315
321
|
await controller.updateModel(payload.botId, payload.model),
|
|
316
322
|
cachedEncode,
|
|
317
323
|
);
|
|
324
|
+
} else if (endpoint === DINGTALK_ENDPOINTS.setReplyContent) {
|
|
325
|
+
if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
|
|
326
|
+
value = await controller.updateReplyContent(payload.botId, payload.replyContent);
|
|
318
327
|
} else if (endpoint === DINGTALK_ENDPOINTS.setBusyMessageMode) {
|
|
319
328
|
if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
|
|
320
329
|
value = await controller.updateBusyMessageMode(
|
|
@@ -33,6 +33,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
|
|
|
33
33
|
import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
|
|
34
34
|
import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
|
|
35
35
|
import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
|
|
36
|
+
import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
|
|
36
37
|
import { createSessionSyncTargetsFor } from '../../session-sync-targets.mjs';
|
|
37
38
|
import {
|
|
38
39
|
accessPolicyProvider,
|
|
@@ -154,15 +155,41 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
154
155
|
|| botConfig.secretRef === LEGACY_FEISHU_SECRET_REF
|
|
155
156
|
? paths.legacyState
|
|
156
157
|
: resolve(paths.bots, botConfig.id, 'state.json');
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
158
|
+
/**
|
|
159
|
+
* Every binding change is announced the moment it is written: a bind before the
|
|
160
|
+
* Session exists, an unbind when the conversation moves to another session or
|
|
161
|
+
* its binding is cleared. Listeners run synchronously.
|
|
162
|
+
*/
|
|
163
|
+
const announcer = createBindingAnnouncer({
|
|
164
|
+
channel: 'feishu',
|
|
165
|
+
emit: (event, payload) => ctx.emit(event, payload),
|
|
166
|
+
authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
|
|
167
|
+
? stateStores.get(botId).snapshot()?.authors ?? null
|
|
168
|
+
: null),
|
|
169
|
+
});
|
|
170
|
+
// The memo key is the bot id, and it is also the id the announcer puts into the
|
|
171
|
+
// event, so a subject without one has to fail loudly: keying it as something
|
|
172
|
+
// else would announce a bot no rule can match and answer `stateForSync` with
|
|
173
|
+
// null. `normalizeBot` always assigns an id - the pre-v2 bot gets a derived one
|
|
174
|
+
// - so this only fires on a programming mistake.
|
|
175
|
+
const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
|
|
176
|
+
announcer,
|
|
177
|
+
StateStore: SessionStateStore,
|
|
178
|
+
statePath: statePathFor,
|
|
179
|
+
keyOf: (subject) => {
|
|
180
|
+
const id = typeof subject === 'string' ? subject : subject?.id;
|
|
181
|
+
if (typeof id !== 'string' || id === '') {
|
|
182
|
+
throw new TypeError('a Feishu bot subject needs an id');
|
|
183
|
+
}
|
|
184
|
+
return id;
|
|
185
|
+
},
|
|
186
|
+
states: stateStores,
|
|
187
|
+
logger,
|
|
188
|
+
});
|
|
189
|
+
// Warm the per-bot state memo now: the synchronous identity lookup can only
|
|
190
|
+
// answer from state that is already loaded in this process, and the first prompt
|
|
191
|
+
// of a session arrives long before any delivery call would load it.
|
|
192
|
+
await prime(configuredBots);
|
|
166
193
|
const stateForBotId = async (botId) => {
|
|
167
194
|
const botConfig = listConfiguredBots().find((bot) => bot.id === botId);
|
|
168
195
|
if (!botConfig) throw new Error('Unknown Feishu bot');
|
|
@@ -277,7 +304,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
277
304
|
});
|
|
278
305
|
},
|
|
279
306
|
deleteState: async ({ botId, config: botConfig }) => {
|
|
280
|
-
|
|
307
|
+
forget(botId);
|
|
281
308
|
try {
|
|
282
309
|
await unlink(statePathFor(botConfig));
|
|
283
310
|
} catch (error) {
|
|
@@ -314,6 +341,8 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
314
341
|
controller,
|
|
315
342
|
deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
|
|
316
343
|
channel: 'feishu', workspaces, coreController, stateFor: stateForBotId,
|
|
344
|
+
// The same store, without the await: it is a memo of already loaded bots.
|
|
345
|
+
stateForSync,
|
|
317
346
|
}),
|
|
318
347
|
ready: supervisor.ready,
|
|
319
348
|
async close() {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload, normalizeBusyMessageMode } from '../../../../src/channels/shared/message-mode.mjs';
|
|
2
|
+
import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
|
|
2
3
|
import { diagnosticFields } from '../../../../src/channels/shared/diagnostic-details.mjs';
|
|
3
4
|
import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../src/channels/shared/connection-error.mjs';
|
|
4
5
|
import { normalizeBotAlias } from '../../../../src/channels/shared/bot-alias.mjs';
|
|
5
6
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
6
7
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
7
|
-
import QRCode from 'qrcode';
|
|
8
|
+
import QRCode from '../../../../src/channels/shared/qrcode.mjs';
|
|
8
9
|
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
9
10
|
import {
|
|
10
11
|
normalizeAgentPresetCatalog,
|
|
@@ -48,6 +49,7 @@ import {
|
|
|
48
49
|
export const FEISHU_ENDPOINTS = Object.freeze({
|
|
49
50
|
...FEISHU_CLIENT_ENDPOINTS,
|
|
50
51
|
setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
|
|
52
|
+
setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
|
|
51
53
|
setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
|
|
52
54
|
setAlias: SET_ALIAS_ENDPOINT,
|
|
53
55
|
setConversationDirectory: FEISHU_CLIENT_ENDPOINTS.setConversationDirectory,
|
|
@@ -483,6 +485,10 @@ function validPayload(endpoint, payload) {
|
|
|
483
485
|
return validAgentPresetPayload(payload)
|
|
484
486
|
? null : '请选择 Agent Preset。';
|
|
485
487
|
}
|
|
488
|
+
if (endpoint === FEISHU_ENDPOINTS.setReplyContent) {
|
|
489
|
+
return validReplyContentPayload(payload)
|
|
490
|
+
? null : '请选择要投递的回复内容。';
|
|
491
|
+
}
|
|
486
492
|
if (endpoint === FEISHU_ENDPOINTS.setBusyMessageMode) {
|
|
487
493
|
return validMessageModePayload(payload)
|
|
488
494
|
? null : '请提交有效的消息处理方式。';
|
|
@@ -813,6 +819,9 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
|
|
|
813
819
|
await controller.updateModel(payload.botId, payload.model),
|
|
814
820
|
{ encodeQr: cachedEncodeQr },
|
|
815
821
|
);
|
|
822
|
+
} else if (endpoint === FEISHU_ENDPOINTS.setReplyContent) {
|
|
823
|
+
if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
|
|
824
|
+
value = await controller.updateReplyContent(payload.botId, payload.replyContent);
|
|
816
825
|
} else if (endpoint === FEISHU_ENDPOINTS.setBusyMessageMode) {
|
|
817
826
|
if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
|
|
818
827
|
value = await controller.updateBusyMessageMode(
|
|
@@ -18,6 +18,7 @@ import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-pr
|
|
|
18
18
|
import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
|
|
19
19
|
import { commandsForChannel } from '../../../../src/channels/shared/command-catalog.mjs';
|
|
20
20
|
import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
|
|
21
|
+
import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
|
|
21
22
|
import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
|
|
22
23
|
import { pluginPaths } from '../shared/production.mjs';
|
|
23
24
|
import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
|
|
@@ -71,14 +72,29 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
71
72
|
const sidecarPath = (botId) => resolve(paths.bots, botId, 'matrix.json');
|
|
72
73
|
const cryptoPath = (botId) => matrixCryptoPathFor(resolve(paths.bots, botId));
|
|
73
74
|
const historyPath = (botId) => matrixRoomHistoryPathFor(resolve(paths.bots, botId));
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
75
|
+
/**
|
|
76
|
+
* Every binding change is announced the moment it is written: a bind before the
|
|
77
|
+
* Session exists, an unbind when the conversation moves to another session or
|
|
78
|
+
* its binding is cleared. Listeners run synchronously.
|
|
79
|
+
*/
|
|
80
|
+
const announcer = createBindingAnnouncer({
|
|
81
|
+
channel: 'matrix',
|
|
82
|
+
emit: (event, payload) => ctx.emit(event, payload),
|
|
83
|
+
authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
|
|
84
|
+
? stateStores.get(botId).snapshot()?.authors ?? null
|
|
85
|
+
: null),
|
|
86
|
+
});
|
|
87
|
+
const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
|
|
88
|
+
announcer,
|
|
89
|
+
StateStore: ResolvedStateStore,
|
|
90
|
+
statePath,
|
|
91
|
+
states: stateStores,
|
|
92
|
+
logger,
|
|
93
|
+
});
|
|
94
|
+
// Warm the per-bot state memo now: the synchronous identity lookup can only
|
|
95
|
+
// answer from state that is already loaded in this process, and the first prompt
|
|
96
|
+
// of a session arrives long before any delivery call would load it.
|
|
97
|
+
await prime(configuredBots.map((bot) => bot.botId));
|
|
82
98
|
const sidecarFor = async (botId) => {
|
|
83
99
|
let sidecar = sidecarStores.get(botId);
|
|
84
100
|
if (!sidecar) {
|
|
@@ -177,8 +193,8 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
177
193
|
});
|
|
178
194
|
},
|
|
179
195
|
deleteState: async ({ botId }) => {
|
|
180
|
-
const state =
|
|
181
|
-
|
|
196
|
+
const state = stateForSync(botId);
|
|
197
|
+
forget(botId);
|
|
182
198
|
const sidecar = sidecarStores.get(botId);
|
|
183
199
|
sidecarStores.delete(botId);
|
|
184
200
|
const crypto = cryptoStores.get(botId);
|
|
@@ -231,6 +247,8 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
231
247
|
controller,
|
|
232
248
|
deliveryAdapter: createDeliveryAdapter({
|
|
233
249
|
channel: 'matrix', workspaces, coreController, stateFor,
|
|
250
|
+
// The same store, without the await: it is a memo of already loaded bots.
|
|
251
|
+
stateForSync,
|
|
234
252
|
}),
|
|
235
253
|
ready: supervisor.ready,
|
|
236
254
|
async close() {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../src/channels/shared/message-mode.mjs';
|
|
2
|
+
import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
|
|
2
3
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
3
4
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
4
5
|
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
|
|
@@ -28,6 +29,7 @@ export const MATRIX_ENDPOINTS = Object.freeze({
|
|
|
28
29
|
setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
|
|
29
30
|
setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
|
|
30
31
|
setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
|
|
32
|
+
setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
|
|
31
33
|
setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
|
|
32
34
|
setAlias: SET_ALIAS_ENDPOINT,
|
|
33
35
|
});
|
|
@@ -101,6 +103,10 @@ function payloadFailure(endpoint, payload) {
|
|
|
101
103
|
return validAgentPresetPayload(payload)
|
|
102
104
|
? null : '请选择 Agent Preset。';
|
|
103
105
|
}
|
|
106
|
+
if (endpoint === MATRIX_ENDPOINTS.setReplyContent) {
|
|
107
|
+
return validReplyContentPayload(payload)
|
|
108
|
+
? null : '请选择要投递的回复内容。';
|
|
109
|
+
}
|
|
104
110
|
if (endpoint === MATRIX_ENDPOINTS.setBusyMessageMode) {
|
|
105
111
|
return validMessageModePayload(payload)
|
|
106
112
|
? null : '请提交有效的消息处理方式。';
|
|
@@ -197,6 +203,10 @@ export function createMatrixRpcHandler(controller) {
|
|
|
197
203
|
if (typeof controller.updateModel !== 'function') throw new Error('Model update is unavailable');
|
|
198
204
|
value = await controller.updateModel(payload.botId, payload.model);
|
|
199
205
|
}
|
|
206
|
+
else if (endpoint === MATRIX_ENDPOINTS.setReplyContent) {
|
|
207
|
+
if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
|
|
208
|
+
value = await controller.updateReplyContent(payload.botId, payload.replyContent);
|
|
209
|
+
}
|
|
200
210
|
else if (endpoint === MATRIX_ENDPOINTS.setBusyMessageMode) {
|
|
201
211
|
if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
|
|
202
212
|
value = await controller.updateBusyMessageMode(payload.botId, payload.busyMessageMode);
|