@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,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
|
}
|
|
@@ -27,6 +27,25 @@ const EXPIRY_RETRY_MAX_MS = 5 * 60_000;
|
|
|
27
27
|
const RESOLVED_ROUTE_TTL_MS = 5 * 60_000;
|
|
28
28
|
const MAX_RESOLVED_ROUTES = 2_048;
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* How a card-driven decision ended, so a channel card can tell "the decision is
|
|
32
|
+
* in" from "still submitting", "try again" and "this card can never work again".
|
|
33
|
+
*
|
|
34
|
+
* A transient Host/RPC failure keeps the approval pending, which makes the
|
|
35
|
+
* press retryable: the card must hand its keyboard back instead of staying
|
|
36
|
+
* `claimed` forever behind a "still submitting" toast.
|
|
37
|
+
*/
|
|
38
|
+
export const APPROVAL_SUBMIT_RESULT = Object.freeze({
|
|
39
|
+
/** The Host accepted the decision; the approval is gone from the queue. */
|
|
40
|
+
SUBMITTED: 'submitted',
|
|
41
|
+
/** Another decision is in flight; keep the card until its outcome is known. */
|
|
42
|
+
BUSY: 'busy',
|
|
43
|
+
/** Nothing was decided and the approval is still pending: press again. */
|
|
44
|
+
RETRYABLE: 'retryable',
|
|
45
|
+
/** The approval is no longer decidable here (resolved, expired, closed). */
|
|
46
|
+
GONE: 'gone',
|
|
47
|
+
});
|
|
48
|
+
|
|
30
49
|
function cleanText(value) {
|
|
31
50
|
return typeof value === 'string' ? value.trim() : '';
|
|
32
51
|
}
|
|
@@ -72,6 +91,7 @@ export function harnessApprovalText(payload, {
|
|
|
72
91
|
toolCall,
|
|
73
92
|
requiresMention = false,
|
|
74
93
|
maxArgumentsLength = 6_000,
|
|
94
|
+
hasButtons = false,
|
|
75
95
|
} = {}) {
|
|
76
96
|
if (!validHarnessApproval(payload)) return null;
|
|
77
97
|
const callId = cleanText(payload.callId);
|
|
@@ -90,8 +110,13 @@ export function harnessApprovalText(payload, {
|
|
|
90
110
|
];
|
|
91
111
|
const reason = printableText(payload.reason);
|
|
92
112
|
if (reason) lines.push(t('原因:{reason}', { reason }));
|
|
93
|
-
|
|
94
|
-
|
|
113
|
+
// A button card carries the intent itself: asking the user to type a decision
|
|
114
|
+
// (or to @ the bot in a group) would be misleading next to the buttons. The
|
|
115
|
+
// plain-text path below stays byte-identical to what it has always sent.
|
|
116
|
+
if (!hasButtons) {
|
|
117
|
+
lines.push('', t(APPROVAL_PROMPT));
|
|
118
|
+
if (requiresMention) lines.push('', t('群聊中请 @机器人 后发送审批决定。'));
|
|
119
|
+
}
|
|
95
120
|
return lines.join('\n');
|
|
96
121
|
}
|
|
97
122
|
|
|
@@ -236,7 +261,9 @@ export class HarnessApprovalQueue {
|
|
|
236
261
|
return;
|
|
237
262
|
}
|
|
238
263
|
if (!decision) {
|
|
239
|
-
|
|
264
|
+
// A button card already tells the user how to decide; repeating
|
|
265
|
+
// the type-the-decision prompt would contradict its buttons.
|
|
266
|
+
if (!pending.interactiveCard) await send(t(APPROVAL_PROMPT));
|
|
240
267
|
return;
|
|
241
268
|
}
|
|
242
269
|
await this.#submit(pending, decision);
|
|
@@ -366,6 +393,10 @@ export class HarnessApprovalQueue {
|
|
|
366
393
|
deliveryCompleted: false,
|
|
367
394
|
replyTail: null,
|
|
368
395
|
submitting: false,
|
|
396
|
+
// Set by a channel renderer once an interactive card really reached the
|
|
397
|
+
// user. It means the card owns the decision guidance and the receipt, so
|
|
398
|
+
// the plain-text prompts/receipts below must stay quiet.
|
|
399
|
+
interactiveCard: false,
|
|
369
400
|
inactive: false,
|
|
370
401
|
resolving: false,
|
|
371
402
|
closedOutcome: null,
|
|
@@ -396,13 +427,20 @@ export class HarnessApprovalQueue {
|
|
|
396
427
|
* (e.g. Feishu approve/reject). Returns false when no matching pending
|
|
397
428
|
* approval is found. Callers may pass the acting user to enforce that only
|
|
398
429
|
* the originating actor can decide.
|
|
430
|
+
*
|
|
431
|
+
* Pass `{ detailed: true }` to get an {@link APPROVAL_SUBMIT_RESULT} instead of
|
|
432
|
+
* a boolean: an interactive card has to tell a retryable submission failure
|
|
433
|
+
* apart from an in-flight decision, one that landed, or an invalid card.
|
|
399
434
|
*/
|
|
400
|
-
async submitByApprovalId(approvalId, outcome, { actor } = {}) {
|
|
435
|
+
async submitByApprovalId(approvalId, outcome, { actor, detailed = false } = {}) {
|
|
401
436
|
const pending = this.#byId.get(cleanText(approvalId));
|
|
402
|
-
|
|
403
|
-
if (
|
|
404
|
-
|
|
405
|
-
return
|
|
437
|
+
const gone = detailed ? APPROVAL_SUBMIT_RESULT.GONE : false;
|
|
438
|
+
if (!pending || pending.inactive || pending.resolving) return gone;
|
|
439
|
+
if (actor !== undefined && pending.actor !== actor) return gone;
|
|
440
|
+
if (pending.submitting) return detailed ? APPROVAL_SUBMIT_RESULT.BUSY : false;
|
|
441
|
+
const result = await this.#submit(pending, outcome);
|
|
442
|
+
if (!detailed) return true;
|
|
443
|
+
return result ?? APPROVAL_SUBMIT_RESULT.RETRYABLE;
|
|
406
444
|
}
|
|
407
445
|
|
|
408
446
|
async handleResolved(resolution) {
|
|
@@ -583,18 +621,19 @@ export class HarnessApprovalQueue {
|
|
|
583
621
|
await this.#transition(next, async () => {
|
|
584
622
|
await this.#notifyResolved(pending, 'resolved', send);
|
|
585
623
|
});
|
|
586
|
-
return;
|
|
624
|
+
return APPROVAL_SUBMIT_RESULT.GONE;
|
|
587
625
|
}
|
|
588
|
-
if (pending.inactive) return;
|
|
626
|
+
if (pending.inactive) return APPROVAL_SUBMIT_RESULT.GONE;
|
|
589
627
|
pending.submitting = false;
|
|
590
628
|
this.#logger.error?.(`[dsh-im:${this.#label}] failed to submit an approval:`, error);
|
|
591
629
|
// The deadline passed while this decision was in flight.
|
|
592
630
|
if (pending.expired) {
|
|
593
631
|
await this.#expire(pending);
|
|
594
|
-
return;
|
|
632
|
+
return APPROVAL_SUBMIT_RESULT.GONE;
|
|
595
633
|
}
|
|
596
634
|
await pending.send(t('审批提交失败,请重新回复「批准」或「拒绝」。')).catch(() => undefined);
|
|
597
|
-
|
|
635
|
+
// The approval is still pending: the caller may offer the press again.
|
|
636
|
+
return APPROVAL_SUBMIT_RESULT.RETRYABLE;
|
|
598
637
|
}
|
|
599
638
|
|
|
600
639
|
const send = pending.send;
|
|
@@ -602,6 +641,7 @@ export class HarnessApprovalQueue {
|
|
|
602
641
|
await this.#transition(next, async () => {
|
|
603
642
|
await this.#notifyResolved(pending, outcome, send);
|
|
604
643
|
});
|
|
644
|
+
return APPROVAL_SUBMIT_RESULT.SUBMITTED;
|
|
605
645
|
}
|
|
606
646
|
|
|
607
647
|
async #notifyResolved(pending, outcome, send = pending.send) {
|
|
@@ -610,11 +650,16 @@ export class HarnessApprovalQueue {
|
|
|
610
650
|
// resolved event cannot replace the confirmed result or notify twice.
|
|
611
651
|
pending.resolutionNotified = true;
|
|
612
652
|
const text = approvalOutcomeText(outcome);
|
|
653
|
+
let deliveredByPresentation = false;
|
|
613
654
|
try {
|
|
614
|
-
|
|
655
|
+
// A card renderer returns true when it already edited the original message
|
|
656
|
+
// into the receipt; the separate terminal text would then be a duplicate
|
|
657
|
+
// (and the pending.send may have been swapped by an interim text reply).
|
|
658
|
+
deliveredByPresentation = (await pending.onResolved?.(text, outcome)) === true;
|
|
615
659
|
} catch (error) {
|
|
616
660
|
this.#logger.warn?.(`[dsh-im:${this.#label}] failed to update a resolved approval:`, error);
|
|
617
661
|
}
|
|
662
|
+
if (deliveredByPresentation) return;
|
|
618
663
|
await send(text).catch(() => undefined);
|
|
619
664
|
}
|
|
620
665
|
|
|
@@ -1351,6 +1351,14 @@ export class HarnessClient {
|
|
|
1351
1351
|
return created.workspace.workspaceId;
|
|
1352
1352
|
}
|
|
1353
1353
|
|
|
1354
|
+
/**
|
|
1355
|
+
* This client can name a Session up front (`session.create` accepts `sessionId`),
|
|
1356
|
+
* which lets a caller bind a conversation before prompt assembly runs.
|
|
1357
|
+
*/
|
|
1358
|
+
get canChooseSessionId() {
|
|
1359
|
+
return true;
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1354
1362
|
async createSession(options = {}) {
|
|
1355
1363
|
const { agentPreset: requestedPreset, ...rpcOptions } = options;
|
|
1356
1364
|
const workspace = rpcOptions.workspace ?? this.#workspace;
|
|
@@ -1362,6 +1370,11 @@ export class HarnessClient {
|
|
|
1362
1370
|
: { workspaceId: await this.workspaceId(rpcOptions) };
|
|
1363
1371
|
const agentPreset = requestedPreset !== undefined ? requestedPreset : this.#agentPreset;
|
|
1364
1372
|
if (agentPreset != null) payload.agentPreset = agentPreset;
|
|
1373
|
+
// The caller may name the Session: it then knows the identity before the
|
|
1374
|
+
// Session exists, which is the only way prompt assembly can see it.
|
|
1375
|
+
if (typeof options.sessionId === 'string' && options.sessionId !== '') {
|
|
1376
|
+
payload.sessionId = options.sessionId;
|
|
1377
|
+
}
|
|
1365
1378
|
const created = await this.rpc('session.create', payload, 30_000, rpcOptions);
|
|
1366
1379
|
if (typeof created?.sessionId !== 'string' || !created.sessionId) {
|
|
1367
1380
|
throw new HarnessTransportError('harness-response-invalid', 'session.create');
|
|
@@ -53,13 +53,24 @@ function sessionWorkspace(sessionId, value) {
|
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
/**
|
|
57
|
+
* @param {string} sessionId - the id the command asked for
|
|
58
|
+
* @param {object} value - the `session.list` response
|
|
59
|
+
* @param {boolean} knownToWorkspace - whether `workspace.list` already accounts for it
|
|
60
|
+
*/
|
|
61
|
+
function sessionSummary(sessionId, value, knownToWorkspace = false) {
|
|
57
62
|
if (!Array.isArray(value?.items)
|
|
58
63
|
|| value.items.some((item) => typeof item?.sessionId !== 'string' || !item.sessionId)) {
|
|
59
64
|
throw new Error('Harness returned an invalid response for session.list');
|
|
60
65
|
}
|
|
61
66
|
const matches = value.items.filter((item) => item.sessionId === sessionId);
|
|
62
67
|
if (matches.length === 0) {
|
|
68
|
+
// An id nobody ever registered is not a transient read failure: a workspace
|
|
69
|
+
// that accounts for the session but has no summary yet may still appear, so
|
|
70
|
+
// only the pair of answers means "no such session".
|
|
71
|
+
if (!knownToWorkspace) {
|
|
72
|
+
throw bindingError('session-not-registered', 'No session with this id is known to Harness');
|
|
73
|
+
}
|
|
63
74
|
throw bindingError('session-summary-unavailable', 'The session is no longer available from Harness');
|
|
64
75
|
}
|
|
65
76
|
if (matches.length !== 1) {
|
|
@@ -91,6 +102,7 @@ export async function adoptRegisteredWorkspaceSession(client, value, options = {
|
|
|
91
102
|
const summary = sessionSummary(
|
|
92
103
|
sessionId,
|
|
93
104
|
await client.rpc('session.list', {}, timeoutMs, options),
|
|
105
|
+
workspace !== undefined || archived === true,
|
|
94
106
|
);
|
|
95
107
|
if (!workspace) {
|
|
96
108
|
if (typeof summary.cwd !== 'string' || !isAbsolute(summary.cwd)
|
|
@@ -85,5 +85,10 @@ export default Object.freeze({
|
|
|
85
85
|
"超时阈值(毫秒)": "Timeout (ms)",
|
|
86
86
|
"Node 版本": "Node version",
|
|
87
87
|
"运行平台": "Platform",
|
|
88
|
-
"无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again."
|
|
88
|
+
"无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again.",
|
|
89
|
+
"DSH 登录状态无效或已过期,请通过有效启动链接重新登录。": "Your DSH session is invalid or expired. Sign in again using a valid launch link.",
|
|
90
|
+
"DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。": "DSH denied this management request (HTTP 403). Check access permissions, trusted hosts and proxy settings. If local-only access is enabled, use an allowed local connection.",
|
|
91
|
+
"DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。": "The DSH management API was not found (HTTP 404). Check the Host and plugin versions and proxy path, then restart and retry.",
|
|
92
|
+
"DSH 管理服务暂时异常,请检查服务状态或稍后重试。": "The DSH management service encountered an error. Check its status or try again later.",
|
|
93
|
+
"DSH 管理请求失败,请检查服务状态和网络连接后重试。": "The DSH management request failed. Check the service status and network connection, then retry."
|
|
89
94
|
});
|
|
@@ -187,6 +187,12 @@ export default {
|
|
|
187
187
|
'跟随默认': 'Follow default',
|
|
188
188
|
'切换预设': 'Switch preset',
|
|
189
189
|
'切换模型': 'Switch model',
|
|
190
|
+
'默认等级': 'Default effort',
|
|
191
|
+
'切换推理等级': 'Switch reasoning effort',
|
|
192
|
+
'第 {page}/{pages} 页 · 共 {total} 个模型': 'Page {page}/{pages} · {total} models',
|
|
193
|
+
'第一页': 'First page',
|
|
194
|
+
'最后一页': 'Last page',
|
|
195
|
+
'当前模型不可用:{model}': 'Current model is unavailable: {model}',
|
|
190
196
|
'当前工作区暂无可用会话。': 'There are no available sessions in the current workspace.',
|
|
191
197
|
'🤖 切换预设': '🤖 Switch preset',
|
|
192
198
|
'🧠 切换模型': '🧠 Switch model',
|
|
@@ -401,6 +407,9 @@ export default {
|
|
|
401
407
|
'任务失败': 'Failed',
|
|
402
408
|
// feishu/bridge.mjs — step push context injection
|
|
403
409
|
'📎 已注入会话上下文': '📎 Context injected',
|
|
410
|
+
// feishu/bridge.mjs — goal rounds opened outside the IM (issue #454)
|
|
411
|
+
'🔄 目标自动续跑': '🔄 Goal auto-continued',
|
|
412
|
+
'🔄 目标自动续跑(第 {round} 轮)': '🔄 Goal auto-continued (round {round})',
|
|
404
413
|
// feishu/feishu-cards.mjs — question card answered state + custom entry (issue #162)
|
|
405
414
|
'✏️ 其他答案…': '✏️ Other answer…',
|
|
406
415
|
'✅ 已回答{progress}': '✅ Answered{progress}',
|
|
@@ -216,6 +216,15 @@ export default {
|
|
|
216
216
|
'/help 显示本帮助': '/help Show this help',
|
|
217
217
|
'{label}机器人与 DeepSeek Harness 连接正常。':
|
|
218
218
|
'The {label} bot is connected to DeepSeek Harness and working normally.',
|
|
219
|
+
// /status details (shared by every text channel that uses TextHarnessBridge).
|
|
220
|
+
'绑定会话:{session}': 'Session: {session}',
|
|
221
|
+
'绑定会话:未绑定(发送消息后自动创建)':
|
|
222
|
+
'Session: not bound yet (created after you send a message)',
|
|
223
|
+
'当前模型:暂无(创建会话后显示)':
|
|
224
|
+
'Current model: not available yet (shown after a Session is created)',
|
|
225
|
+
'Agent Preset(预设):{preset}': 'Agent Preset: {preset}',
|
|
226
|
+
'运行中任务:有(发送 /stop 可停止)':
|
|
227
|
+
'Running task: yes (send /stop to stop it)',
|
|
219
228
|
'{label}机器人凭据缺失,请移除后重新接入。':
|
|
220
229
|
'{label} bot credentials are missing. Remove the bot and connect it again.',
|
|
221
230
|
'{label}连接未就绪,插件会自动重试。':
|
|
@@ -30,4 +30,18 @@ export default {
|
|
|
30
30
|
'This Telegram bot already has a Webhook configured. Remove the Webhook from the original service and try again.',
|
|
31
31
|
'Telegram机器人': 'Telegram Bot',
|
|
32
32
|
' Bot API 长轮询': ' Bot API long polling',
|
|
33
|
+
// Approval button card (batch 1): buttons, terminal receipts and dead-card
|
|
34
|
+
// notices. Keys match the literals passed through t() in approval-card.mjs.
|
|
35
|
+
'✅ 批准一次': '✅ Approve once',
|
|
36
|
+
'✅ 已批准(仅本次)': '✅ Approved (this time only)',
|
|
37
|
+
'❌ 已拒绝': '❌ Rejected',
|
|
38
|
+
'⏰ 已过期': '⏰ Expired',
|
|
39
|
+
'⛔ 已失效': '⛔ No longer valid',
|
|
40
|
+
'正在提交审批决定,请稍候。': 'Submitting the approval decision, please wait.',
|
|
41
|
+
'该审批已处理,无需重复操作。': 'This approval was already handled. No need to act again.',
|
|
42
|
+
'该审批已过期,已自动拒绝。': 'This approval expired and was rejected automatically.',
|
|
43
|
+
'该审批已被新提示取代,请使用最新一条。':
|
|
44
|
+
'This approval was superseded by a newer prompt; use the latest one.',
|
|
45
|
+
'该审批已失效,请等待新的审批提示。':
|
|
46
|
+
'This approval is no longer valid; wait for a new approval prompt.',
|
|
33
47
|
};
|
|
@@ -103,4 +103,14 @@ export default Object.freeze({
|
|
|
103
103
|
'运行平台': 'Платформа',
|
|
104
104
|
'无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。':
|
|
105
105
|
'Нет доступа к административному API DSH. Проверьте соединение с DSH или войдите заново.',
|
|
106
|
+
'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。':
|
|
107
|
+
'Сеанс DSH недействителен или истёк. Войдите снова по действующей ссылке запуска.',
|
|
108
|
+
'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。':
|
|
109
|
+
'DSH отклонил запрос управления (HTTP 403). Проверьте права доступа, доверенные адреса и настройки прокси. Если разрешён только локальный доступ, используйте разрешённое локальное подключение.',
|
|
110
|
+
'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。':
|
|
111
|
+
'API управления DSH не найден (HTTP 404). Проверьте версии Host и плагина, а также путь прокси, затем перезапустите и повторите попытку.',
|
|
112
|
+
'DSH 管理服务暂时异常,请检查服务状态或稍后重试。':
|
|
113
|
+
'В службе управления DSH произошла ошибка. Проверьте её состояние или повторите попытку позже.',
|
|
114
|
+
'DSH 管理请求失败,请检查服务状态和网络连接后重试。':
|
|
115
|
+
'Запрос управления DSH не выполнен. Проверьте состояние службы и подключение к сети, затем повторите попытку.',
|
|
106
116
|
});
|
|
@@ -166,6 +166,12 @@ export default {
|
|
|
166
166
|
'跟随默认': 'Как по умолчанию',
|
|
167
167
|
'切换预设': 'Сменить пресет',
|
|
168
168
|
'切换模型': 'Сменить модель',
|
|
169
|
+
'默认等级': 'По умолчанию',
|
|
170
|
+
'切换推理等级': 'Сменить уровень рассуждений',
|
|
171
|
+
'第 {page}/{pages} 页 · 共 {total} 个模型': 'Страница {page}/{pages} · моделей: {total}',
|
|
172
|
+
'第一页': 'Первая страница',
|
|
173
|
+
'最后一页': 'Последняя страница',
|
|
174
|
+
'当前模型不可用:{model}': 'Текущая модель недоступна: {model}',
|
|
169
175
|
'当前工作区暂无可用会话。': 'В текущей рабочей области нет доступных сессий.',
|
|
170
176
|
'🤖 切换预设': '🤖 Сменить пресет',
|
|
171
177
|
'🧠 切换模型': '🧠 Сменить модель',
|
|
@@ -362,6 +368,8 @@ export default {
|
|
|
362
368
|
'Не удалось безопасно остановить фоновую задачу. Найдите соответствующую задачу в Harness и остановите её.',
|
|
363
369
|
'任务失败': 'Не удалось',
|
|
364
370
|
'📎 已注入会话上下文': '📎 Контекст добавлен',
|
|
371
|
+
'🔄 目标自动续跑': '🔄 Цель продолжена автоматически',
|
|
372
|
+
'🔄 目标自动续跑(第 {round} 轮)': '🔄 Цель продолжена автоматически (раунд {round})',
|
|
365
373
|
'✏️ 其他答案…': '✏️ Другой ответ…',
|
|
366
374
|
'✅ 已回答{progress}': '✅ Ответ дан{progress}',
|
|
367
375
|
'✅ 已选择:{label}': '✅ Выбрано: {label}',
|
|
@@ -211,6 +211,15 @@ export default {
|
|
|
211
211
|
'/version 查看插件版本': '/version Показать версию плагина',
|
|
212
212
|
'/help 显示本帮助': '/help Показать эту справку',
|
|
213
213
|
'{label}机器人与 DeepSeek Harness 连接正常。': 'Бот {label} и DeepSeek Harness соединены нормально.',
|
|
214
|
+
// /status details (shared by every text channel that uses TextHarnessBridge).
|
|
215
|
+
'绑定会话:{session}': 'Сессия: {session}',
|
|
216
|
+
'绑定会话:未绑定(发送消息后自动创建)':
|
|
217
|
+
'Сессия: ещё не привязана (создаётся после вашего сообщения)',
|
|
218
|
+
'当前模型:暂无(创建会话后显示)':
|
|
219
|
+
'Текущая модель: пока недоступна (появится после создания сессии)',
|
|
220
|
+
'Agent Preset(预设):{preset}': 'Agent Preset: {preset}',
|
|
221
|
+
'运行中任务:有(发送 /stop 可停止)':
|
|
222
|
+
'Выполняется задача: да (отправьте /stop, чтобы остановить)',
|
|
214
223
|
'{label}机器人凭据缺失,请移除后重新接入。': 'Нет учётных данных бота {label}. Удалите его и подключите заново.',
|
|
215
224
|
'{label}连接未就绪,插件会自动重试。': 'Соединение {label} не готово, плагин повторит попытку автоматически.',
|
|
216
225
|
'{label}机器人已接入,消息连接暂未就绪。': 'Бот {label} подключён, но соединение для сообщений пока не готово.',
|
|
@@ -27,4 +27,18 @@ export default {
|
|
|
27
27
|
'У этого бота Telegram уже настроен Webhook. Удалите Webhook в исходном сервисе и повторите попытку.',
|
|
28
28
|
'Telegram机器人': 'Бот Telegram',
|
|
29
29
|
' Bot API 长轮询': ' Долгий опрос Bot API',
|
|
30
|
+
// Approval button card (batch 1): buttons, terminal receipts and dead-card
|
|
31
|
+
// notices. Keys match the literals passed through t() in approval-card.mjs.
|
|
32
|
+
'✅ 批准一次': '✅ Одобрить один раз',
|
|
33
|
+
'✅ 已批准(仅本次)': '✅ Одобрено (только в этот раз)',
|
|
34
|
+
'❌ 已拒绝': '❌ Отклонено',
|
|
35
|
+
'⏰ 已过期': '⏰ Просрочено',
|
|
36
|
+
'⛔ 已失效': '⛔ Больше не действует',
|
|
37
|
+
'正在提交审批决定,请稍候。': 'Отправляю решение о подтверждении, подождите.',
|
|
38
|
+
'该审批已处理,无需重复操作。': 'Это подтверждение уже обработано. Повторять не нужно.',
|
|
39
|
+
'该审批已过期,已自动拒绝。': 'Срок подтверждения истёк, операция отклонена автоматически.',
|
|
40
|
+
'该审批已被新提示取代,请使用最新一条。':
|
|
41
|
+
'Это подтверждение заменено более новым запросом. Используйте последний.',
|
|
42
|
+
'该审批已失效,请等待新的审批提示。':
|
|
43
|
+
'Это подтверждение больше не действует. Дождитесь нового запроса.',
|
|
30
44
|
};
|
|
@@ -439,6 +439,11 @@ function modelErrorMessage(error, action) {
|
|
|
439
439
|
|
|
440
440
|
async function boundSession(harness, state, key, options) {
|
|
441
441
|
if (typeof state?.sessionFor !== 'function') return null;
|
|
442
|
+
// A DS Bot binding may exist before this IM chat has received a message.
|
|
443
|
+
// Resolve its current part rather than creating an unrelated IM session.
|
|
444
|
+
if (typeof harness?.resolveDsBotSession === 'function') {
|
|
445
|
+
await harness.resolveDsBotSession(key);
|
|
446
|
+
}
|
|
442
447
|
const sessionId = state.sessionFor(key);
|
|
443
448
|
if (typeof sessionId !== 'string' || !sessionId) return null;
|
|
444
449
|
if (typeof harness?.workspaceSession !== 'function') {
|