@xmanrui/dsh-im 5.8.0 → 5.9.1
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 +45 -8
- package/README.md +56 -8
- package/docs/preset-workspaces.md +37 -0
- package/lib/client.js +66 -7
- 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/inbound-ttl-rpc.mjs +1 -1
- package/plugin-src/host/index.mjs +25 -2
- package/plugin-src/host/modern-harness-api.mjs +3 -0
- package/plugin-src/host/sidebar-settings.mjs +1 -2
- package/plugin-src/host/update-rpc.mjs +1 -1
- package/plugin-src/management-rpc.mjs +25 -3
- package/scripts/telegram-menu-scopes.mjs +57 -0
- package/scripts/verify-interface-language.mjs +60 -15
- package/scripts/verify-lan-management.mjs +58 -5
- package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
- package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
- package/src/channels/email/email-runtime.mjs +27 -8
- package/src/channels/email/transports/imap-smtp.mjs +21 -11
- package/src/channels/feishu/bridge.mjs +296 -13
- 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/diagnostics.mjs +6 -1
- package/src/channels/shared/i18n-en/feishu.mjs +9 -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/diagnostics.mjs +10 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +8 -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
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { t } from './i18n.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Shared foundation for interactive cards that carry a one-shot button press.
|
|
7
|
+
*
|
|
8
|
+
* Every carded channel needs the same four things, and four independent
|
|
9
|
+
* implementations already existed (Feishu card keys, QQ opaque tokens, DingTalk
|
|
10
|
+
* revisions, Telegram question nonces). This module provides them once:
|
|
11
|
+
*
|
|
12
|
+
* - a versioned, bounded callback namespace (`<prefix>|<nonce>|<action>`) so a
|
|
13
|
+
* keyboard press is attributable to exactly one presentation;
|
|
14
|
+
* - a nonce registry with TTL and capacity limits, so a dead card cannot grow
|
|
15
|
+
* memory forever;
|
|
16
|
+
* - a synchronous first-press claim, so two taps (or two clients) execute once;
|
|
17
|
+
* - one set of Chinese notices for pressed/expired/superseded cards.
|
|
18
|
+
*
|
|
19
|
+
* Cards that also need to re-check live data (a list shrank, a session was
|
|
20
|
+
* deleted) should `claim()` first and then `settle(nonce, 'stale')` when the
|
|
21
|
+
* re-check fails.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Telegram rejects callback_data longer than 64 bytes. */
|
|
25
|
+
export const ACTION_CARD_CALLBACK_MAX_BYTES = 64;
|
|
26
|
+
|
|
27
|
+
const CALLBACK_PREFIX_PATTERN = /^[a-z][a-z0-9]{0,7}$/u;
|
|
28
|
+
const NONCE_PATTERN = /^[A-Za-z0-9_-]{1,32}$/u;
|
|
29
|
+
const ACTION_PATTERN = /^[A-Za-z0-9_-]{1,16}$/u;
|
|
30
|
+
const DEFAULT_NONCE_BYTES = 9;
|
|
31
|
+
|
|
32
|
+
export const ACTION_CARD_STATUS = Object.freeze({
|
|
33
|
+
/** Rendered, waiting for its first press. */
|
|
34
|
+
ACTIVE: 'active',
|
|
35
|
+
/** Pressed; the handler owns the outcome now. */
|
|
36
|
+
CLAIMED: 'claimed',
|
|
37
|
+
/** Handled successfully. */
|
|
38
|
+
RESOLVED: 'resolved',
|
|
39
|
+
/** TTL elapsed (approval timeout, dead keyboard). */
|
|
40
|
+
EXPIRED: 'expired',
|
|
41
|
+
/** A newer card replaced this one in the same conversation. */
|
|
42
|
+
SUPERSEDED: 'superseded',
|
|
43
|
+
/** The live re-check after a press found the underlying state changed. */
|
|
44
|
+
STALE: 'stale',
|
|
45
|
+
/** The owner revoked the card (route closed, approval withdrawn). */
|
|
46
|
+
REVOKED: 'revoked',
|
|
47
|
+
/** No such nonce (process restarted, foreign payload). */
|
|
48
|
+
UNKNOWN: 'unknown',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const LIVE_STATUSES = new Set([ACTION_CARD_STATUS.ACTIVE, ACTION_CARD_STATUS.CLAIMED]);
|
|
52
|
+
const TERMINAL_STATUSES = new Set([
|
|
53
|
+
ACTION_CARD_STATUS.RESOLVED,
|
|
54
|
+
ACTION_CARD_STATUS.EXPIRED,
|
|
55
|
+
ACTION_CARD_STATUS.SUPERSEDED,
|
|
56
|
+
ACTION_CARD_STATUS.STALE,
|
|
57
|
+
ACTION_CARD_STATUS.REVOKED,
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
/** One notice per card state; channels override the wording per surface. */
|
|
61
|
+
export const ACTION_CARD_STATE_TEXTS = Object.freeze({
|
|
62
|
+
[ACTION_CARD_STATUS.ACTIVE]: '正在处理,请稍候。',
|
|
63
|
+
[ACTION_CARD_STATUS.CLAIMED]: '正在提交,请稍候。',
|
|
64
|
+
[ACTION_CARD_STATUS.RESOLVED]: '该操作已处理,无需重复操作。',
|
|
65
|
+
[ACTION_CARD_STATUS.EXPIRED]: '该操作已过期,请重新打开。',
|
|
66
|
+
[ACTION_CARD_STATUS.SUPERSEDED]: '该操作已被新操作取代,请使用最新一条。',
|
|
67
|
+
[ACTION_CARD_STATUS.STALE]: '该内容已变化,请重新打开后再操作。',
|
|
68
|
+
[ACTION_CARD_STATUS.REVOKED]: '该操作已失效,请重新打开。',
|
|
69
|
+
[ACTION_CARD_STATUS.UNKNOWN]: '该操作已失效或不存在。',
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* A random, URL-safe presentation identity.
|
|
74
|
+
* 9 bytes → 12 base64url characters: collision-safe per conversation and small
|
|
75
|
+
* enough that the whole callback payload stays far under 64 bytes.
|
|
76
|
+
*/
|
|
77
|
+
export function createActionNonce(byteLength = DEFAULT_NONCE_BYTES) {
|
|
78
|
+
if (!Number.isInteger(byteLength) || byteLength < 1 || byteLength > 24) {
|
|
79
|
+
throw new TypeError('An action card nonce needs 1..24 random bytes');
|
|
80
|
+
}
|
|
81
|
+
return randomBytes(byteLength).toString('base64url');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Build one versioned callback namespace, e.g. `ap1|<nonce>|<action>`.
|
|
86
|
+
* Encoding validates every token before emitting it, so a button can always be
|
|
87
|
+
* attributed and can never exceed Telegram's callback budget.
|
|
88
|
+
*/
|
|
89
|
+
export function createCallbackNamespace(prefix) {
|
|
90
|
+
if (typeof prefix !== 'string' || !CALLBACK_PREFIX_PATTERN.test(prefix)) {
|
|
91
|
+
throw new TypeError('An action card callback prefix is invalid');
|
|
92
|
+
}
|
|
93
|
+
const maxBytes = ACTION_CARD_CALLBACK_MAX_BYTES;
|
|
94
|
+
return Object.freeze({
|
|
95
|
+
prefix,
|
|
96
|
+
maxBytes,
|
|
97
|
+
encode({ nonce, action } = {}) {
|
|
98
|
+
if (typeof nonce !== 'string' || !NONCE_PATTERN.test(nonce)) {
|
|
99
|
+
throw new TypeError('An action card nonce is invalid');
|
|
100
|
+
}
|
|
101
|
+
if (typeof action !== 'string' || !ACTION_PATTERN.test(action)) {
|
|
102
|
+
throw new TypeError('An action card action is invalid');
|
|
103
|
+
}
|
|
104
|
+
const data = `${prefix}|${nonce}|${action}`;
|
|
105
|
+
if (Buffer.byteLength(data, 'utf8') > maxBytes) {
|
|
106
|
+
throw new TypeError(`An action card callback must be at most ${maxBytes} bytes`);
|
|
107
|
+
}
|
|
108
|
+
return data;
|
|
109
|
+
},
|
|
110
|
+
parse(data) {
|
|
111
|
+
if (typeof data !== 'string') return null;
|
|
112
|
+
const parts = data.split('|');
|
|
113
|
+
if (parts.length !== 3 || parts[0] !== prefix) return null;
|
|
114
|
+
const [, nonce, action] = parts;
|
|
115
|
+
if (!NONCE_PATTERN.test(nonce) || !ACTION_PATTERN.test(action)) return null;
|
|
116
|
+
return { nonce, action };
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The notice shown for a dead or already-handled card. */
|
|
122
|
+
export function actionCardStateText(status, texts = {}) {
|
|
123
|
+
const override = texts && typeof texts === 'object' ? texts[status] : undefined;
|
|
124
|
+
const fallback = ACTION_CARD_STATE_TEXTS[status]
|
|
125
|
+
?? (texts && typeof texts === 'object' ? texts[ACTION_CARD_STATUS.UNKNOWN] : undefined)
|
|
126
|
+
?? ACTION_CARD_STATE_TEXTS[ACTION_CARD_STATUS.UNKNOWN];
|
|
127
|
+
return t(typeof override === 'string' && override ? override : fallback);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* In-memory presentation registry for one channel.
|
|
132
|
+
*
|
|
133
|
+
* Entries live for `ttlMs`; a terminal entry is kept until then so a late press
|
|
134
|
+
* still gets "已处理/已过期" instead of a generic "不存在". At most
|
|
135
|
+
* `maxEntries` cards are remembered (oldest is evicted first) and a new card in
|
|
136
|
+
* a conversation supersedes the previous live one.
|
|
137
|
+
*/
|
|
138
|
+
export class ActionCardRegistry {
|
|
139
|
+
#ttlMs;
|
|
140
|
+
#maxEntries;
|
|
141
|
+
#now;
|
|
142
|
+
#createNonce;
|
|
143
|
+
#entries = new Map();
|
|
144
|
+
|
|
145
|
+
constructor({
|
|
146
|
+
ttlMs = 3_600_000,
|
|
147
|
+
maxEntries = 256,
|
|
148
|
+
now = Date.now,
|
|
149
|
+
createNonce = createActionNonce,
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
152
|
+
throw new TypeError('An action card TTL must be a positive number');
|
|
153
|
+
}
|
|
154
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
|
|
155
|
+
throw new TypeError('An action card capacity must be a positive integer');
|
|
156
|
+
}
|
|
157
|
+
if (typeof now !== 'function') throw new TypeError('An action card clock must be a function');
|
|
158
|
+
if (typeof createNonce !== 'function') {
|
|
159
|
+
throw new TypeError('An action card nonce factory must be a function');
|
|
160
|
+
}
|
|
161
|
+
this.#ttlMs = ttlMs;
|
|
162
|
+
this.#maxEntries = maxEntries;
|
|
163
|
+
this.#now = now;
|
|
164
|
+
this.#createNonce = createNonce;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
get size() {
|
|
168
|
+
return this.#entries.size;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Register one presentation. Issuing a new card in the same conversation
|
|
173
|
+
* retires the previous live one — one conversation shows one working card.
|
|
174
|
+
*/
|
|
175
|
+
issue({ conversationKey, kind = '', payload = {}, ttlMs } = {}) {
|
|
176
|
+
const key = typeof conversationKey === 'string' ? conversationKey.trim() : '';
|
|
177
|
+
if (!key) throw new TypeError('An action card requires a conversation key');
|
|
178
|
+
const now = this.#now();
|
|
179
|
+
const lifetime = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : this.#ttlMs;
|
|
180
|
+
// Drop long-dead cards so TTL memory is reclaimed even when presses stop.
|
|
181
|
+
this.purge();
|
|
182
|
+
this.revokeConversation(key, { status: ACTION_CARD_STATUS.SUPERSEDED });
|
|
183
|
+
|
|
184
|
+
let nonce = null;
|
|
185
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
186
|
+
const candidate = this.#createNonce();
|
|
187
|
+
if (typeof candidate !== 'string' || !NONCE_PATTERN.test(candidate)) {
|
|
188
|
+
throw new TypeError('An action card nonce must be 1..32 URL-safe characters');
|
|
189
|
+
}
|
|
190
|
+
if (!this.#entries.has(candidate)) {
|
|
191
|
+
nonce = candidate;
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (nonce === null) throw new Error('Could not allocate a unique action card nonce');
|
|
196
|
+
|
|
197
|
+
const entry = {
|
|
198
|
+
nonce,
|
|
199
|
+
conversationKey: key,
|
|
200
|
+
kind: typeof kind === 'string' ? kind : '',
|
|
201
|
+
payload: payload && typeof payload === 'object' ? payload : {},
|
|
202
|
+
status: ACTION_CARD_STATUS.ACTIVE,
|
|
203
|
+
createdAt: now,
|
|
204
|
+
expiresAt: now + lifetime,
|
|
205
|
+
claimedAt: null,
|
|
206
|
+
settledAt: null,
|
|
207
|
+
};
|
|
208
|
+
this.#entries.set(nonce, entry);
|
|
209
|
+
this.#enforceCapacity();
|
|
210
|
+
return entry;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Read an entry (and lazily mark it expired when its TTL elapsed). */
|
|
214
|
+
get(nonce) {
|
|
215
|
+
const entry = this.#lookup(nonce);
|
|
216
|
+
if (!entry) return null;
|
|
217
|
+
this.#expireIfNeeded(entry);
|
|
218
|
+
return entry;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Claim the first press synchronously. The caller must call this before its
|
|
223
|
+
* first `await`, so a second tap cannot also see the card as active.
|
|
224
|
+
*/
|
|
225
|
+
claim(nonce) {
|
|
226
|
+
const entry = this.#lookup(nonce);
|
|
227
|
+
if (!entry) return { status: ACTION_CARD_STATUS.UNKNOWN, entry: null };
|
|
228
|
+
this.#expireIfNeeded(entry);
|
|
229
|
+
const liveStatus = entry.status;
|
|
230
|
+
if (liveStatus === ACTION_CARD_STATUS.ACTIVE) {
|
|
231
|
+
entry.status = ACTION_CARD_STATUS.CLAIMED;
|
|
232
|
+
entry.claimedAt = this.#now();
|
|
233
|
+
}
|
|
234
|
+
// `active` means this caller won the claim; any other value is a refusal.
|
|
235
|
+
return { status: liveStatus, entry };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Give a claimed card its keyboard back after a submission that failed but is
|
|
240
|
+
* still retryable (a transient RPC error, a dropped response). Without this a
|
|
241
|
+
* card stays `claimed` forever and every later press is answered with "still
|
|
242
|
+
* submitting", so the only recovery is typing the decision as text.
|
|
243
|
+
*
|
|
244
|
+
* Only a live claim can be released: a card already resolved, expired or
|
|
245
|
+
* superseded must stay dead, otherwise a stale tap could decide a newer
|
|
246
|
+
* approval. Returns the released entry, or null when nothing was released.
|
|
247
|
+
*/
|
|
248
|
+
releaseClaim(nonce) {
|
|
249
|
+
const entry = this.#lookup(nonce);
|
|
250
|
+
if (!entry) return null;
|
|
251
|
+
this.#expireIfNeeded(entry);
|
|
252
|
+
if (entry.status !== ACTION_CARD_STATUS.CLAIMED) return null;
|
|
253
|
+
entry.status = ACTION_CARD_STATUS.ACTIVE;
|
|
254
|
+
entry.claimedAt = null;
|
|
255
|
+
return entry;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Move a live card to a terminal state. Returns false when there is nothing
|
|
260
|
+
* left to settle (unknown, expired, or already settled).
|
|
261
|
+
*/
|
|
262
|
+
settle(nonce, status = ACTION_CARD_STATUS.RESOLVED) {
|
|
263
|
+
if (!TERMINAL_STATUSES.has(status)) {
|
|
264
|
+
throw new TypeError('An action card can only settle to a terminal status');
|
|
265
|
+
}
|
|
266
|
+
const entry = this.#lookup(nonce);
|
|
267
|
+
if (!entry) return false;
|
|
268
|
+
this.#expireIfNeeded(entry);
|
|
269
|
+
if (!LIVE_STATUSES.has(entry.status)) return false;
|
|
270
|
+
entry.status = status;
|
|
271
|
+
entry.settledAt = this.#now();
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The one live card of a conversation, if any. */
|
|
276
|
+
activeFor(conversationKey) {
|
|
277
|
+
for (const entry of this.#entries.values()) {
|
|
278
|
+
if (entry.conversationKey !== conversationKey) continue;
|
|
279
|
+
this.#expireIfNeeded(entry);
|
|
280
|
+
if (LIVE_STATUSES.has(entry.status)) return entry;
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Retire every live card of one conversation (route closed, list changed). */
|
|
286
|
+
revokeConversation(conversationKey, { status = ACTION_CARD_STATUS.SUPERSEDED } = {}) {
|
|
287
|
+
if (!TERMINAL_STATUSES.has(status)) {
|
|
288
|
+
throw new TypeError('An action card can only be revoked to a terminal status');
|
|
289
|
+
}
|
|
290
|
+
let revoked = 0;
|
|
291
|
+
for (const entry of this.#entries.values()) {
|
|
292
|
+
if (entry.conversationKey !== conversationKey) continue;
|
|
293
|
+
this.#expireIfNeeded(entry);
|
|
294
|
+
if (!LIVE_STATUSES.has(entry.status)) continue;
|
|
295
|
+
entry.status = status;
|
|
296
|
+
entry.settledAt = this.#now();
|
|
297
|
+
revoked += 1;
|
|
298
|
+
}
|
|
299
|
+
return revoked;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Drop every entry whose TTL elapsed; returns how many were removed. */
|
|
303
|
+
purge() {
|
|
304
|
+
const now = this.#now();
|
|
305
|
+
let removed = 0;
|
|
306
|
+
for (const [nonce, entry] of this.#entries) {
|
|
307
|
+
if (now >= entry.expiresAt) {
|
|
308
|
+
this.#entries.delete(nonce);
|
|
309
|
+
removed += 1;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return removed;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
#lookup(nonce) {
|
|
316
|
+
return typeof nonce === 'string' ? this.#entries.get(nonce) ?? null : null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
#expireIfNeeded(entry) {
|
|
320
|
+
if (!LIVE_STATUSES.has(entry.status)) return;
|
|
321
|
+
if (this.#now() < entry.expiresAt) return;
|
|
322
|
+
entry.status = ACTION_CARD_STATUS.EXPIRED;
|
|
323
|
+
entry.settledAt = entry.expiresAt;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
#enforceCapacity() {
|
|
327
|
+
while (this.#entries.size > this.#maxEntries) {
|
|
328
|
+
this.#entries.delete(this.#entries.keys().next().value);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -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>',
|