@xmanrui/dsh-im 5.8.0 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.en.md +42 -7
  2. package/README.md +53 -7
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +34 -2
  5. package/lib/index.js +329 -326
  6. package/package.json +3 -1
  7. package/plugin-src/client/connection-error.js +1 -1
  8. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  9. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  10. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  11. package/plugin-src/host/channels/qq/production.mjs +2 -1
  12. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  13. package/plugin-src/host/channels/shared/production.mjs +32 -3
  14. package/plugin-src/host/channels/slack/production.mjs +2 -1
  15. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  16. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  17. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  18. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  19. package/plugin-src/host/delivery-adapter.mjs +122 -1
  20. package/plugin-src/host/delivery-service.mjs +40 -0
  21. package/plugin-src/host/ds-bot-client.mjs +28 -2
  22. package/plugin-src/host/index.mjs +24 -1
  23. package/plugin-src/host/modern-harness-api.mjs +3 -0
  24. package/scripts/telegram-menu-scopes.mjs +57 -0
  25. package/scripts/verify-interface-language.mjs +60 -15
  26. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  27. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  28. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  29. package/src/channels/feishu/bridge.mjs +46 -10
  30. package/src/channels/feishu/feishu-cards.mjs +96 -25
  31. package/src/channels/qq/qq-menu.mjs +3 -4
  32. package/src/channels/shared/action-card.mjs +331 -0
  33. package/src/channels/shared/bot-workspace-store.mjs +123 -8
  34. package/src/channels/shared/command-catalog.mjs +20 -5
  35. package/src/channels/shared/conversation/describe.mjs +116 -0
  36. package/src/channels/shared/conversation-state-store.mjs +62 -0
  37. package/src/channels/shared/diagnostic-details.mjs +38 -0
  38. package/src/channels/shared/harness-approval.mjs +58 -13
  39. package/src/channels/shared/harness-client.mjs +13 -0
  40. package/src/channels/shared/harness-session-binding.mjs +13 -1
  41. package/src/channels/shared/i18n-en/feishu.mjs +6 -0
  42. package/src/channels/shared/i18n-en/shared-a.mjs +9 -0
  43. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  44. package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
  45. package/src/channels/shared/i18n-ru/shared-a.mjs +9 -0
  46. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  47. package/src/channels/shared/model-command.mjs +5 -0
  48. package/src/channels/shared/preset-workspaces.mjs +48 -0
  49. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  50. package/src/channels/shared/status-command.mjs +159 -0
  51. package/src/channels/shared/text-harness-bridge.mjs +86 -4
  52. package/src/channels/shared/workspace-command.mjs +20 -12
  53. package/src/channels/shared/workspace-session.mjs +30 -5
  54. package/src/channels/telegram/approval-card.mjs +379 -0
  55. package/src/channels/telegram/telegram-api.mjs +10 -1
  56. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  57. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  58. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -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
- lines.push('', t(APPROVAL_PROMPT));
94
- if (requiresMention) lines.push('', t('群聊中请 @机器人 后发送审批决定。'));
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
- await send(t(APPROVAL_PROMPT));
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
- if (!pending || pending.inactive || pending.resolving || pending.submitting) return false;
403
- if (actor !== undefined && pending.actor !== actor) return false;
404
- await this.#submit(pending, outcome);
405
- return true;
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
- return;
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
- await pending.onResolved?.(text);
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
- function sessionSummary(sessionId, value) {
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)
@@ -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',
@@ -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
  };
@@ -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
  '🧠 切换模型': '🧠 Сменить модель',
@@ -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') {
@@ -0,0 +1,48 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { sameWorkspacePath } from './default-workspace.mjs';
4
+ import { validateAgentPresetId } from './agent-preset.mjs';
5
+
6
+ /** Register a preset's group without changing any bot workspace or existing session binding. */
7
+ export async function ensurePresetWorkspace(harness, workspace, preset, catalog, options = {}) {
8
+ const id = validateAgentPresetId(preset);
9
+ if (
10
+ !id ||
11
+ typeof harness?.isUngroupedWorkspace !== 'function' ||
12
+ !(await harness.isUngroupedWorkspace(workspace))
13
+ )
14
+ return workspace;
15
+ const directory = join(workspace, 'presets', id);
16
+ await mkdir(directory, { recursive: true, mode: 0o700 });
17
+ const listing = await harness.rpc('workspace.list', {}, 30000, options);
18
+ if (!Array.isArray(listing?.items)) throw new Error('Harness returned an invalid workspace list');
19
+ let existing;
20
+ for (const item of listing.items) {
21
+ if (await sameWorkspacePath(item.path, directory)) {
22
+ existing = item;
23
+ break;
24
+ }
25
+ }
26
+ // A user may rename an automatically created group. Preserve that title.
27
+ if (existing && existing.title !== id) return directory;
28
+ const result = existing
29
+ ? { workspace: existing }
30
+ : await harness.rpc('workspace.create', { path: directory }, 30000, options);
31
+ if (!result?.workspace?.workspaceId) throw new Error('Harness returned an invalid workspace');
32
+ if (result.created === false && result.workspace.title !== id) return directory;
33
+ const label = catalog?.items.find((item) => item.id === id)?.label ?? id;
34
+ const title = listing.items.some(
35
+ (item) => item.title === label && item.workspaceId !== result.workspace.workspaceId,
36
+ )
37
+ ? `${label}(${id})`
38
+ : label;
39
+ if (result.workspace.title !== title) {
40
+ await harness.rpc(
41
+ 'workspace.rename',
42
+ { workspaceId: result.workspace.workspaceId, title },
43
+ 30000,
44
+ options,
45
+ );
46
+ }
47
+ return directory;
48
+ }
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
3
- import { normalizeDiagnosticDetails } from './diagnostic-details.mjs';
3
+ import { normalizeDiagnosticDetails, safeDiagnosticMessage } from './diagnostic-details.mjs';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  let installedDependencies;
@@ -27,13 +27,19 @@ function dependencies() {
27
27
  return installedDependencies;
28
28
  }
29
29
 
30
- /** Attach only safe facts; never copy QR contents, exception text or stack traces. */
30
+ /** Attach only safe facts: no QR contents, no stack traces.
31
+ * The deepest cause's message is included when it reads as plain technical
32
+ * text (see `safeDiagnosticMessage`); it is the only fact that separates
33
+ * `QRCode.toDataURL is not a function` from a zlib failure with the same shape. */
31
34
  export function qrEncodingError(cause) {
32
35
  if (cause?.name === 'AbortError') return cause;
33
36
  const evidence = extractConnectionEvidence(cause);
37
+ const leaf = evidence.chain.at(-1);
38
+ const causeMessage = safeDiagnosticMessage(leaf?.message);
34
39
  return connectionStageError(new Error('QR encoding failed', { cause }), 'qr.encode', undefined, {
35
40
  qrEncoder: 'qrcode', qrRenderer: 'png',
36
41
  errorTypes: evidence.errors.map(error => error.type),
42
+ ...(causeMessage ? { causeMessage } : {}),
37
43
  dependencies: dependencies(),
38
44
  });
39
45
  }
@@ -0,0 +1,159 @@
1
+ import { t } from './i18n.mjs';
2
+
3
+ /** Long enough to tell sessions apart in a chat, short enough to read. */
4
+ const SESSION_ID_DISPLAY_LENGTH = 12;
5
+
6
+ /**
7
+ * Optional /status fields must not hold the reply open when the Host is stuck.
8
+ * Three seconds is well above a healthy local RPC and short enough that the
9
+ * connection line is never buried behind a frozen Session/models read.
10
+ */
11
+ export const STATUS_FIELD_TIMEOUT_MS = 3_000;
12
+
13
+ function shortenedSessionId(sessionId) {
14
+ return sessionId.length > SESSION_ID_DISPLAY_LENGTH
15
+ ? `${sessionId.slice(0, SESSION_ID_DISPLAY_LENGTH)}…`
16
+ : sessionId;
17
+ }
18
+
19
+ /**
20
+ * The workspace the current conversation actually runs in: an explicit
21
+ * per-conversation pin when present, otherwise the bot-wide default.
22
+ */
23
+ function readWorkspace(harness, conversationKey) {
24
+ if (typeof harness?.currentConversationWorkspace === 'function'
25
+ && typeof conversationKey === 'string' && conversationKey) {
26
+ const workspace = harness.currentConversationWorkspace(conversationKey);
27
+ if (typeof workspace === 'string' && workspace) return workspace;
28
+ }
29
+ if (typeof harness?.currentWorkspace === 'function') {
30
+ const workspace = harness.currentWorkspace();
31
+ if (typeof workspace === 'string' && workspace) return workspace;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ async function readPreset(harness, options) {
37
+ if (typeof harness?.agentPresetSettings !== 'function') return null;
38
+ const settings = await harness.agentPresetSettings(options);
39
+ const preset = settings?.agentPreset;
40
+ if (typeof preset !== 'string' || !preset) return t('跟随 Host 默认');
41
+ const item = settings?.agentPresetCatalog?.items?.find((entry) => entry?.id === preset);
42
+ return item?.label ? `${item.label}(${preset})` : preset;
43
+ }
44
+
45
+ async function readModel(session, options) {
46
+ if (typeof session?.models !== 'function') return null;
47
+ const catalog = await session.models(options);
48
+ const current = catalog?.current;
49
+ if (typeof current?.provider !== 'string' || !current.provider
50
+ || typeof current?.model !== 'string' || !current.model) return null;
51
+ return `${current.provider}/${current.model}`;
52
+ }
53
+
54
+ async function readRunning(session, options) {
55
+ if (typeof session?.isRunning !== 'function') return false;
56
+ return (await session.isRunning(options)) === true;
57
+ }
58
+
59
+ /** Give the optional reads their own deadline, without cancelling the turn. */
60
+ function fieldReadOptions(signal, timeoutMs) {
61
+ const timeout = AbortSignal.timeout(timeoutMs);
62
+ return { signal: signal ? AbortSignal.any([signal, timeout]) : timeout };
63
+ }
64
+
65
+ /** A status field is optional: one failing read must not fail the command. */
66
+ async function settled(operation) {
67
+ try {
68
+ return await operation();
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * A status field is optional AND must not outlive its deadline.
76
+ *
77
+ * The abort signal alone is not enough: the real Host chain
78
+ * (`agentPresetSettings()` reads the preset directory before it re-checks the
79
+ * signal) can ignore it and never settle, which would hold the whole reply
80
+ * open. Race the read against its own timer so the deadline holds no matter
81
+ * how the underlying RPC behaves; the signal still lets cooperative readers
82
+ * cancel their work early.
83
+ */
84
+ function settledWithin(operation, timeoutMs) {
85
+ return new Promise((resolve) => {
86
+ let settledAlready = false;
87
+ const finish = (value) => {
88
+ if (settledAlready) return false;
89
+ settledAlready = true;
90
+ clearTimeout(timer);
91
+ resolve(value ?? null);
92
+ return true;
93
+ };
94
+ const timer = setTimeout(() => finish(null), timeoutMs);
95
+ timer.unref?.();
96
+ (async () => operation())().then(finish, () => finish(null));
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Render one readable /status reply for the text channels.
102
+ *
103
+ * The first line is the historical connection confirmation. Everything after
104
+ * it is best-effort: a workspace, session binding, model or Agent Preset that
105
+ * cannot be read is omitted (or explained) instead of turning the command into
106
+ * a failure. The running-task line appears only when this chat's bound session
107
+ * is actually running, so the common idle case stays short. Optional reads use
108
+ * a bounded signal ({@link STATUS_FIELD_TIMEOUT_MS}) so a frozen Host cannot
109
+ * make the command hang.
110
+ */
111
+ export async function runStatusCommand({
112
+ descriptor,
113
+ harness,
114
+ state,
115
+ conversationKey,
116
+ signal,
117
+ fieldTimeoutMs = STATUS_FIELD_TIMEOUT_MS,
118
+ } = {}) {
119
+ if (!harness || typeof harness.ensureRunning !== 'function') {
120
+ throw new TypeError('A Harness client with ensureRunning is required');
121
+ }
122
+ const options = signal ? { signal } : {};
123
+ await harness.ensureRunning(options);
124
+ const fieldTimeout = Number.isSafeInteger(fieldTimeoutMs) && fieldTimeoutMs > 0
125
+ ? fieldTimeoutMs
126
+ : STATUS_FIELD_TIMEOUT_MS;
127
+ const fieldOptions = fieldReadOptions(signal, fieldTimeout);
128
+
129
+ const label = descriptor?.label ?? 'Telegram';
130
+ const lines = [t('{label}机器人与 DeepSeek Harness 连接正常。', { label })];
131
+
132
+ const workspace = await settled(() => readWorkspace(harness, conversationKey));
133
+ if (workspace) lines.push(t('工作区:{workspace}', { workspace }));
134
+
135
+ const sessionId = await settled(async () => (typeof state?.sessionFor === 'function'
136
+ ? state.sessionFor(conversationKey)
137
+ : null));
138
+ const boundSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
139
+ lines.push(boundSessionId
140
+ ? t('绑定会话:{session}', { session: shortenedSessionId(boundSessionId) })
141
+ : t('绑定会话:未绑定(发送消息后自动创建)'));
142
+
143
+ const session = boundSessionId
144
+ ? await settled(() => (typeof harness.workspaceSession === 'function'
145
+ ? harness.workspaceSession(boundSessionId, conversationKey)
146
+ : null))
147
+ : null;
148
+ const [model, preset, running] = await Promise.all([
149
+ session ? settledWithin(() => readModel(session, fieldOptions), fieldTimeout) : null,
150
+ settledWithin(() => readPreset(harness, fieldOptions), fieldTimeout),
151
+ session ? settledWithin(() => readRunning(session, fieldOptions), fieldTimeout) : false,
152
+ ]);
153
+ if (model) lines.push(t('当前模型:{model}', { model }));
154
+ else if (!session) lines.push(t('当前模型:暂无(创建会话后显示)'));
155
+ if (preset) lines.push(t('Agent Preset(预设):{preset}', { preset }));
156
+ if (running === true) lines.push(t('运行中任务:有(发送 /stop 可停止)'));
157
+
158
+ return { message: lines.join('\n') };
159
+ }