@xmanrui/dsh-im 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "4.8.0",
3
+ "version": "4.9.0",
4
4
  "description": "把九种 IM 机器人和公网 AI Office 接入本机 DeepSeek Harness。 Connect nine IM channels and a public AI Office to a local DeepSeek Harness.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
@@ -245,14 +245,15 @@ const CSS = String.raw`
245
245
  .dim-contextSwitch:checked { border-color: var(--dsw-alias-state-business-primary, #3370ff); background: var(--dsw-alias-state-business-primary, #3370ff); }
246
246
  .dim-contextSwitch:checked::before { transform: translateX(13px); background: #fff; }
247
247
  .dim-contextFields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 3px 12px; }
248
- .dim-contextField { min-width: 0; min-height: 30px; display: flex; align-items: center; gap: 6px; }
248
+ .dim-contextField { position: relative; min-width: 0; min-height: 30px; display: flex; align-items: center; gap: 6px; }
249
249
  .dim-contextField input { flex: none; width: 14px; height: 14px; margin: 0; accent-color: var(--dsw-alias-state-business-primary, #3370ff); }
250
250
  .dim-contextFieldText { min-width: 0; display: grid; grid-template-columns: max-content max-content; align-items: center; column-gap: 5px; overflow-wrap: anywhere; }
251
251
  .dim-contextFieldName { min-width: 0; line-height: 17px; cursor: pointer; }
252
252
  .dim-contextFieldKey { min-width: 0; grid-column: 1 / -1; color: var(--dsw-alias-label-tertiary, #8f959e); font: 10px/14px ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; cursor: pointer; }
253
- .dim-contextFieldHelp { position: relative; }
253
+ .dim-contextFieldHelp { position: static; }
254
254
  .dim-contextFieldHelpButton { width: 16px; height: 16px; font-size: 10px; }
255
255
  .dim-contextTooltip.dim-contextFieldTooltip { top: calc(100% + 6px); right: 0; left: auto; width: min(280px, calc(100vw - 72px)); }
256
+ .dim-contextField:nth-child(odd) .dim-contextFieldTooltip { right: auto; left: 0; }
256
257
  .dim-contextEditorHeader { position: relative; flex-wrap: wrap; }
257
258
  .dim-contextEditorTitle { min-width: 0; display: inline-flex; align-items: center; gap: 6px; }
258
259
  .dim-contextEditorTitle > label { font-weight: 500; }
@@ -81,6 +81,7 @@ const HELP_TEXT_LINES = [
81
81
  '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)',
82
82
  '/workspace 工作区序号或绝对路径 切换工作区',
83
83
  '/workspacelist 列出工作区绝对路径',
84
+ '/ws、/wsl、/workspaces 工作区命令别名',
84
85
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
85
86
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
86
87
  '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
@@ -76,6 +76,7 @@ import {
76
76
  MENU_PAGE_SIZE,
77
77
  PRESET_FOLLOW_DEFAULT_SENTINEL,
78
78
  STEER_CUSTOM_SENTINEL,
79
+ approvalCard,
79
80
  completionCard,
80
81
  customSteerCard,
81
82
  helpCard,
@@ -83,6 +84,7 @@ import {
83
84
  menuHelpText,
84
85
  modelCard,
85
86
  presetCard,
87
+ questionCard,
86
88
  sessionListCard,
87
89
  statusCard,
88
90
  steerCard,
@@ -107,7 +109,7 @@ const WATCH_COMMAND = /^\/watch(?:\s+([^\s]+))?$/i;
107
109
  const UNWATCH_COMMAND = /^\/unwatch(?:\s+([^\s]+))?$/i;
108
110
  const WATCHLIST_COMMAND = /^\/watchlist$/i;
109
111
  const SESSION_LIST_PREFIX = /^\/(?:sessionlist|sessions)(?:\s|$)/i;
110
- const WORKSPACE_LIST_COMMAND = /^\/workspacelist$/i;
112
+ const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)$/i;
111
113
  const NUMBER_REPLY = /^\d{1,2}$/;
112
114
  /** A displayed menu stays number-tappable for this long. */
113
115
  const MENU_TTL_MS = 10 * 60_000;
@@ -146,7 +148,34 @@ const REPAIR_URL_HOSTS = new Set([
146
148
 
147
149
  const ARCHIVED_COMMAND = /^\/archived(?:\s+(on|off))?$/i;
148
150
  /** Matches fast card commands that should not be queued behind a running task. */
149
- const CARD_COMMAND = /^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|watchlist|archived(?:\s+(on|off))?)$/i;
151
+ const CARD_COMMAND = /^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|workspaces|wsl|watchlist|archived(?:\s+(on|off))?)$/i;
152
+
153
+ /** Pretty-print a tool call's arguments for an approval card. */
154
+ function operationArguments(toolCall) {
155
+ const source = toolCall?.arguments;
156
+ if (source !== null && typeof source === 'object') {
157
+ try {
158
+ return JSON.stringify(source, null, 2);
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+ if (typeof source !== 'string') return null;
164
+ const raw = printableText(source);
165
+ // Harness treats an empty tool argument string as an empty object.
166
+ if (!raw) return source === '' ? '{}' : null;
167
+ try {
168
+ return JSON.stringify(JSON.parse(raw), null, 2);
169
+ } catch {
170
+ return raw;
171
+ }
172
+ }
173
+
174
+ /** Strip control characters so the approval card text stays clean. */
175
+ function printableText(value) {
176
+ return String(value ?? '')
177
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '');
178
+ }
150
179
 
151
180
  function isFeishuLocalCommand(text, { hasImages = false, hasFiles = false } = {}) {
152
181
  if (hasImages || hasFiles || typeof text !== 'string') return false;
@@ -471,6 +500,8 @@ export class FeishuHarnessBridge {
471
500
  /** Earliest completion that still needs delivery for each watch. */
472
501
  #failedWatchSeqs = new Map();
473
502
  #cardDataTimeoutMs;
503
+ /** When true, approval/question interactions render as Feishu cards (buttons). */
504
+ #interactionCards = true;
474
505
 
475
506
  constructor({
476
507
  client,
@@ -490,6 +521,7 @@ export class FeishuHarnessBridge {
490
521
  repairLinkWaitMs = REPAIR_LINK_WAIT_MS,
491
522
  cardDataTimeoutMs = CARD_DATA_TIMEOUT_MS,
492
523
  replyTimeoutMs = 600_000,
524
+ interactionCards = true,
493
525
  logger = console,
494
526
  signal,
495
527
  }) {
@@ -528,6 +560,7 @@ export class FeishuHarnessBridge {
528
560
  this.#repairLinkWaitMs = repairLinkWaitMs;
529
561
  this.#cardDataTimeoutMs = cardDataTimeoutMs;
530
562
  this.#replyTimeoutMs = replyTimeoutMs;
563
+ this.#interactionCards = interactionCards === true;
531
564
  this.#logger = logger;
532
565
  this.#approvals = new HarnessApprovalQueue({ label: 'Feishu', logger });
533
566
  this.#signal = signal;
@@ -1644,10 +1677,15 @@ export class FeishuHarnessBridge {
1644
1677
  }
1645
1678
  const conversationType = route.key.startsWith('p2p:') ? 'direct'
1646
1679
  : route.key.startsWith('group:') ? 'group' : null;
1680
+ const isInteractionResponse = resolvedAction.startsWith('approve:')
1681
+ || resolvedAction.startsWith('reject:')
1682
+ || resolvedAction.startsWith('answer:');
1647
1683
  const access = evaluateInboundAccess(this.#accessPolicy, {
1648
1684
  conversationType,
1649
1685
  senderIds: operatorOpenId,
1650
- isCommand: true,
1686
+ // These buttons are the card equivalent of an ordinary approval or
1687
+ // question reply. Every other card action remains command-gated.
1688
+ isCommand: !isInteractionResponse,
1651
1689
  });
1652
1690
  if (!access.allowed) {
1653
1691
  if (access.reason === 'command-not-allowed') {
@@ -1710,7 +1748,7 @@ export class FeishuHarnessBridge {
1710
1748
  return;
1711
1749
  }
1712
1750
  }
1713
- await this.#handleCardAction(resolvedAction, entry);
1751
+ await this.#handleCardAction(resolvedAction, { ...entry, actor: entry.operatorOpenId });
1714
1752
  }, {
1715
1753
  lane: isStop || isRealSteer ? 'control' : 'regular',
1716
1754
  coalesceStop: isStop,
@@ -1868,10 +1906,49 @@ export class FeishuHarnessBridge {
1868
1906
  sessionPage = 0,
1869
1907
  sessionLimit = null,
1870
1908
  selections = [],
1909
+ actor = null,
1871
1910
  }) {
1872
1911
  // Confirmations triggered by a card interaction stay anchored to the
1873
1912
  // card's message so they land inside the same Feishu topic.
1874
1913
  const reply = (text) => this.#send(chatId, text, { replyTo: messageId });
1914
+ // Approval card buttons: approve:<approvalId> / reject:<approvalId>
1915
+ if (action.startsWith('approve:') || action.startsWith('reject:')) {
1916
+ const sep = action.indexOf(':');
1917
+ const approvalId = action.slice(sep + 1);
1918
+ const outcome = action.startsWith('approve:') ? 'allowed-once' : 'rejected';
1919
+ // Bind the decision to the operator so another allowed group member
1920
+ // cannot decide someone else's approval.
1921
+ const submitted = await this.#approvals.submitByApprovalId(approvalId, outcome, { actor });
1922
+ if (!submitted) {
1923
+ await reply(t('该审批已处理或不存在,无需重复操作。')).catch(() => undefined);
1924
+ }
1925
+ return;
1926
+ }
1927
+ // Question option buttons: answer:<interactionId>:<index>:<optionLabel>
1928
+ if (action.startsWith('answer:')) {
1929
+ const rest = action.slice('answer:'.length);
1930
+ const firstSep = rest.indexOf(':');
1931
+ if (firstSep !== -1) {
1932
+ const interactionId = rest.slice(0, firstSep);
1933
+ const afterId = rest.slice(firstSep + 1);
1934
+ const indexSep = afterId.indexOf(':');
1935
+ const indexText = indexSep === -1 ? afterId : afterId.slice(0, indexSep);
1936
+ const optionLabel = indexSep === -1 ? '' : afterId.slice(indexSep + 1);
1937
+ const qKey = this.#interactionKeys.get(interactionId);
1938
+ const pending = qKey ? this.#pendingInteractions.get(qKey) : null;
1939
+ // Only the actor who started the interaction may answer it, and the
1940
+ // card must still target the current question (a stale card from an
1941
+ // earlier question in a multi-question interaction must not submit).
1942
+ if (pending && pending.kind === 'question' && !pending.submitting
1943
+ && pending.actor === actor
1944
+ && Number(indexText) === pending.index) {
1945
+ await this.#submitQuestionAnswer(pending, optionLabel, { chatId });
1946
+ } else {
1947
+ await reply(INTERACTION_RESOLVED_TEXT()).catch(() => undefined);
1948
+ }
1949
+ }
1950
+ return;
1951
+ }
1875
1952
  if (action === 'sessions' || /^sessions:\d+$/.test(action)) {
1876
1953
  const page = action === 'sessions' ? 0 : Number(action.slice('sessions:'.length));
1877
1954
  await this.#showSessions(
@@ -3585,7 +3662,18 @@ export class FeishuHarnessBridge {
3585
3662
  const question = pending.questions[pending.index];
3586
3663
  if (!question) return;
3587
3664
 
3588
- pending.answers.push(harnessAnswerForQuestion(question, text));
3665
+ await this.#submitQuestionAnswer(pending, text, {
3666
+ chatId: event.message.chat_id,
3667
+ messageId,
3668
+ });
3669
+ }
3670
+
3671
+ async #submitQuestionAnswer(pending, answerText, { chatId, messageId } = {}) {
3672
+ const question = pending.questions[pending.index];
3673
+ if (!question) return;
3674
+ pending.chatId = chatId ?? pending.chatId;
3675
+
3676
+ pending.answers.push(harnessAnswerForQuestion(question, answerText));
3589
3677
  pending.index += 1;
3590
3678
  if (pending.index < pending.questions.length) {
3591
3679
  if (pending.claimedReplyMessageId === messageId) {
@@ -3603,6 +3691,7 @@ export class FeishuHarnessBridge {
3603
3691
  }
3604
3692
 
3605
3693
  pending.submitting = true;
3694
+ const key = pending.key;
3606
3695
  try {
3607
3696
  await pending.interaction.respond({
3608
3697
  ok: true,
@@ -3620,7 +3709,9 @@ export class FeishuHarnessBridge {
3620
3709
  if (error?.code === 'interaction-not-pending') {
3621
3710
  this.#rememberResolvedInteraction(key, pending);
3622
3711
  this.#clearPendingInteraction(key, pending.interactionId);
3623
- await this.#send(event.message.chat_id, INTERACTION_RESOLVED_TEXT(), { replyTo: event.message.message_id }).catch(() => undefined);
3712
+ if (chatId && messageId) {
3713
+ await this.#send(chatId, INTERACTION_RESOLVED_TEXT(), { replyTo: messageId }).catch(() => undefined);
3714
+ }
3624
3715
  return;
3625
3716
  }
3626
3717
  pending.submitting = false;
@@ -3628,8 +3719,10 @@ export class FeishuHarnessBridge {
3628
3719
  pending.index -= 1;
3629
3720
  this.#status.lastError = '回答提交失败。';
3630
3721
  this.#logger.error?.('[dsh-feishu] failed to answer a Harness interaction');
3631
- await this.#send(event.message.chat_id, t('回答提交失败,请重新发送当前问题的答案。'))
3632
- .catch(() => undefined);
3722
+ if (chatId) {
3723
+ await this.#send(chatId, t('回答提交失败,请重新发送当前问题的答案。'))
3724
+ .catch(() => undefined);
3725
+ }
3633
3726
  }
3634
3727
  }
3635
3728
 
@@ -3645,6 +3738,32 @@ export class FeishuHarnessBridge {
3645
3738
  actor,
3646
3739
  requiresMention,
3647
3740
  send: (text) => this.#send(chatId, text, { replyTo: replyToMessageId }),
3741
+ // Approvals render as interactive cards with approve/reject buttons by
3742
+ // default. Set the bridge `interactionCards` option (or
3743
+ // DSH_IM_INTERACTION_CARDS=0) to keep the plain-text reply flow.
3744
+ ...(this.#interactionCards
3745
+ ? {
3746
+ render: async (pending) => {
3747
+ // Show the approval as an interactive card with approve/reject buttons.
3748
+ await this.#sendCard(
3749
+ chatId,
3750
+ approvalCard({
3751
+ toolName: pending.toolCall?.name ?? pending.payload?.toolName,
3752
+ operation: operationArguments(pending.toolCall),
3753
+ reason: pending.payload?.reason,
3754
+ approvalId: pending.approvalId,
3755
+ }),
3756
+ { key, replyTo: replyToMessageId },
3757
+ ).catch(async () => {
3758
+ // Fall back to the plain-text approval if the card cannot be
3759
+ // sent. If the text send also fails, let the error propagate so
3760
+ // the pending approval is not marked as presented and the
3761
+ // existing retry/reconnect logic can run.
3762
+ await this.#send(chatId, pending.text, { replyTo: replyToMessageId });
3763
+ });
3764
+ },
3765
+ }
3766
+ : {}),
3648
3767
  })) return;
3649
3768
 
3650
3769
  // Approval requests return above; the existing question state machine stays unchanged.
@@ -3738,18 +3857,53 @@ export class FeishuHarnessBridge {
3738
3857
  async #presentInteraction(pending) {
3739
3858
  const question = pending.questions[pending.index];
3740
3859
  if (!question) return;
3741
- const messageId = await this.#send(
3742
- pending.chatId,
3743
- harnessQuestionText(
3744
- question,
3745
- pending.index,
3746
- pending.questions.length,
3747
- { requiresMention: pending.requiresMention },
3748
- ),
3749
- // Reply to the message that started the turn so the question lands in
3750
- // the same Feishu thread/topic instead of the group's default area.
3751
- { replyTo: pending.replyToMessageId },
3752
- );
3860
+ const options = Array.isArray(question?.options) ? question.options : [];
3861
+ // Single-choice questions with options render as interactive cards by
3862
+ // default. Multi-select or free-text questions and the text reply flow
3863
+ // remain when `interactionCards` is disabled (or DSH_IM_INTERACTION_CARDS=0).
3864
+ const interactive = this.#interactionCards
3865
+ && options.length > 0
3866
+ && question.multiSelect !== true;
3867
+ let messageId;
3868
+ if (interactive) {
3869
+ // Single-choice question with options: render each option as a button.
3870
+ messageId = await this.#sendCard(
3871
+ pending.chatId,
3872
+ questionCard({
3873
+ interactionId: pending.interactionId,
3874
+ header: question.header,
3875
+ question: question.question,
3876
+ detail: question.detail,
3877
+ options,
3878
+ index: pending.index,
3879
+ total: pending.questions.length,
3880
+ }),
3881
+ { key: pending.key, replyTo: pending.replyToMessageId },
3882
+ ).catch(async () => {
3883
+ // Fall back to the plain-text question if the card cannot be sent.
3884
+ // If the text send also fails, let the error propagate so the pending
3885
+ // question is not marked as presented and the existing retry logic runs.
3886
+ return this.#send(
3887
+ pending.chatId,
3888
+ harnessQuestionText(question, pending.index, pending.questions.length, {
3889
+ requiresMention: pending.requiresMention,
3890
+ }),
3891
+ { replyTo: pending.replyToMessageId },
3892
+ );
3893
+ });
3894
+ } else {
3895
+ // Multi-select or free-text questions keep the plain-text reply flow.
3896
+ messageId = await this.#send(
3897
+ pending.chatId,
3898
+ harnessQuestionText(
3899
+ question,
3900
+ pending.index,
3901
+ pending.questions.length,
3902
+ { requiresMention: pending.requiresMention },
3903
+ ),
3904
+ { replyTo: pending.replyToMessageId },
3905
+ );
3906
+ }
3753
3907
  if (messageId) {
3754
3908
  pending.questionMessageIds.add(messageId);
3755
3909
  if (pending.inactive) this.#rememberResolvedInteraction(pending.key, pending);
@@ -492,6 +492,7 @@ export function menuHelpText() {
492
492
  '/session ID 绑定已有会话',
493
493
  '/workspacelist 列出工作区',
494
494
  '/workspace 工作区序号或绝对路径 切换工作区',
495
+ '/ws、/wsl、/workspaces 工作区命令别名',
495
496
  '/new 开启全新会话',
496
497
  '',
497
498
  '📊 状态 / 压缩',
@@ -595,6 +596,7 @@ export function helpCard(extraTextLines = []) {
595
596
  { tag: 'hr' },
596
597
  { tag: 'div', text: markdown([
597
598
  t(HELP_TEXT_COMMANDS),
599
+ t('/ws、/wsl、/workspaces 工作区命令别名'),
598
600
  t('`/version` — 查看插件版本'),
599
601
  t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
600
602
  ].join('\n') + extraText) },
@@ -867,3 +869,70 @@ export function customSteerCard() {
867
869
  ];
868
870
  return cardWith(t('➕ 自定义指令'), elements);
869
871
  }
872
+
873
+ /**
874
+ * Interactive approval card with approve / reject buttons. Action values carry
875
+ * the approvalId so the card callback can submit the decision:
876
+ * approve:<approvalId> / reject:<approvalId>
877
+ * `requiresMention` is advisory; a button click is itself the operator's
878
+ * explicit intent, so it does not need an @ mention in groups.
879
+ */
880
+ export function approvalCard({ toolName, operation, reason, approvalId }) {
881
+ const elements = [];
882
+ if (toolName) {
883
+ elements.push({ tag: 'div', text: markdown(t('工具:{tool}', { tool: String(toolName) })) });
884
+ }
885
+ if (operation) {
886
+ // Cap the operation text so an oversized argument list cannot overflow the
887
+ // card (the plain-text path rejects >6000 chars; here we truncate so the
888
+ // approve/reject buttons still render).
889
+ const MAX_OPERATION_CHARS = 6_000;
890
+ const op = String(operation);
891
+ const shown = op.length > MAX_OPERATION_CHARS
892
+ ? `${op.slice(0, MAX_OPERATION_CHARS)}\n…(操作参数过长,已截断)`
893
+ : op;
894
+ elements.push({ tag: 'div', text: markdown(t('操作参数:\n{operation}', { operation: shown })) });
895
+ }
896
+ if (reason) {
897
+ elements.push({ tag: 'div', text: markdown(t('原因:{reason}', { reason: String(reason) })) });
898
+ }
899
+ elements.push(
900
+ { tag: 'hr' },
901
+ buttonPair(t('✅ 批准'), `approve:${approvalId}`, t('❌ 拒绝'), `reject:${approvalId}`),
902
+ );
903
+ return cardWith(t('🔐 工具审批'), elements);
904
+ }
905
+
906
+ /**
907
+ * Interactive question card. When the question carries options, each option is
908
+ * rendered as its own button; the selected option label is submitted via a
909
+ * card callback. Multi-select questions fall back to the plain-text flow (the
910
+ * caller decides), because a multi-select needs a confirm step.
911
+ * Action: answer:<interactionId>:<optionLabel>
912
+ */
913
+ export function questionCard({ interactionId, header, question, detail, options, index, total }) {
914
+ const elements = [];
915
+ const progress = total > 1 ? `(${index + 1}/${total})` : '';
916
+ if (header) elements.push({ tag: 'div', text: markdown(String(header)) });
917
+ const qText = typeof question === 'string' && question.trim() ? question : t('请输入你的回答。');
918
+ elements.push({ tag: 'div', text: markdown(String(qText)) });
919
+ if (detail) elements.push({ tag: 'div', text: markdown(String(detail)) });
920
+
921
+ if (Array.isArray(options) && options.length > 0) {
922
+ elements.push({ tag: 'hr' });
923
+ for (const option of options) {
924
+ const label = typeof option?.label === 'string' ? option.label : '';
925
+ if (!label) continue;
926
+ const description = typeof option?.description === 'string' && option.description.trim()
927
+ ? option.description.trim()
928
+ : '';
929
+ // Include the option description in the button so the user sees the full
930
+ // meaning (mirrors the text form "1. label — description").
931
+ const buttonText = description ? `${label}\n${description}` : label;
932
+ // Action carries the question index so a stale card from a previous
933
+ // question cannot be applied to the current one: answer:<interactionId>:<index>:<label>
934
+ elements.push(button(buttonText, `answer:${interactionId}:${index}:${label}`));
935
+ }
936
+ }
937
+ return cardWith(t('❓ 请补充信息{progress}', { progress }), elements);
938
+ }
@@ -288,6 +288,11 @@ export class FeishuRuntime {
288
288
  groupResponseMode: this.#groupResponseMode,
289
289
  repair: this.#repair,
290
290
  replyTimeoutMs: this.#replyTimeoutMs,
291
+ // Interaction cards (approval/question buttons) are on by default.
292
+ // Set DSH_IM_INTERACTION_CARDS=0 to fall back to plain-text replies.
293
+ interactionCards: !['0', 'false', 'no', 'off'].includes(
294
+ String(process.env.DSH_IM_INTERACTION_CARDS ?? '').trim().toLowerCase(),
295
+ ),
291
296
  signal,
292
297
  logger: this.#logger,
293
298
  });
@@ -43,6 +43,9 @@ export const SLASH_COMMAND_MANIFEST = Object.freeze([
43
43
  { command: 'compact', icon: 'ai-block_outlined', default: '压缩当前会话上下文', en_us: 'Compact the current session' },
44
44
  { command: 'sessionlist', icon: 'chat-ai_outlined', default: '列出会话', en_us: 'List sessions' },
45
45
  { command: 'workspacelist', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
46
+ { command: 'workspaces', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
47
+ { command: 'wsl', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' },
48
+ { command: 'ws', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' },
46
49
  { command: 'watch', icon: 'flag_outlined', default: '关注一个会话', en_us: 'Watch a session' },
47
50
  { command: 'unwatch', icon: 'clear_outlined', default: '取消关注会话', en_us: 'Unwatch a session' },
48
51
  { command: 'watchlist', icon: 'flag_outlined', default: '查看关注列表', en_us: 'List watched sessions' },
@@ -90,6 +90,7 @@ function helpText() {
90
90
  t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
91
91
  t('/workspace 工作区序号或绝对路径 切换工作区'),
92
92
  t('/workspacelist 列出工作区绝对路径'),
93
+ t('/ws、/wsl、/workspaces 工作区命令别名'),
93
94
  t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
94
95
  t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
95
96
  t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
@@ -245,6 +245,10 @@ export class HarnessApprovalQueue {
245
245
  await this.#rejectInteraction(interaction, payload);
246
246
  return true;
247
247
  }
248
+ // Optional channel-provided renderer. When present, the approval is shown
249
+ // as an interactive card (e.g. Feishu approve/reject buttons) instead of
250
+ // plain text. Channels that don't provide one keep the text-reply path.
251
+ const render = typeof context?.render === 'function' ? context.render : null;
248
252
 
249
253
  const text = harnessApprovalText(payload, {
250
254
  toolCall: interaction.toolCall,
@@ -267,6 +271,7 @@ export class HarnessApprovalQueue {
267
271
  actor,
268
272
  requiresMention: context.requiresMention === true,
269
273
  send,
274
+ render,
270
275
  text,
271
276
  presented: false,
272
277
  presentationTask: null,
@@ -287,6 +292,20 @@ export class HarnessApprovalQueue {
287
292
  return true;
288
293
  }
289
294
 
295
+ /**
296
+ * Submit an approval decision by id, as triggered by a channel card button
297
+ * (e.g. Feishu approve/reject). Returns false when no matching pending
298
+ * approval is found. Callers may pass the acting user to enforce that only
299
+ * the originating actor can decide.
300
+ */
301
+ async submitByApprovalId(approvalId, outcome, { actor } = {}) {
302
+ const pending = this.#byId.get(cleanText(approvalId));
303
+ if (!pending || pending.inactive || pending.resolving || pending.submitting) return false;
304
+ if (actor !== undefined && pending.actor !== actor) return false;
305
+ await this.#submit(pending, outcome);
306
+ return true;
307
+ }
308
+
290
309
  async handleResolved(resolution) {
291
310
  if (resolution?.kind !== 'approval') return false;
292
311
  const pending = this.#byId.get(cleanText(resolution.interactionId));
@@ -353,7 +372,11 @@ export class HarnessApprovalQueue {
353
372
  if (this.#routes.get(pending.key)?.items[0] !== pending
354
373
  || pending.inactive || pending.resolving || pending.presented) return;
355
374
  if (pending.presentationTask) return pending.presentationTask;
356
- const task = Promise.resolve().then(() => pending.send(pending.text));
375
+ // A channel-provided renderer shows the approval as an interactive card
376
+ // (e.g. approve/reject buttons); otherwise fall back to plain text.
377
+ const task = pending.render
378
+ ? Promise.resolve().then(() => pending.render(pending, pending.send))
379
+ : Promise.resolve().then(() => pending.send(pending.text));
357
380
  pending.presentationTask = task;
358
381
  try {
359
382
  await task;
@@ -434,6 +434,11 @@ export class HarnessReplyTracker {
434
434
  return this.#finished;
435
435
  }
436
436
 
437
+ /** The highest event seq consumed so far; advances as the turn produces events. */
438
+ get lastSeq() {
439
+ return this.#lastSeq;
440
+ }
441
+
437
442
  get answer() {
438
443
  return this.#latestText.trim();
439
444
  }
@@ -1435,8 +1440,14 @@ export class HarnessClient {
1435
1440
  promptAccepted = true;
1436
1441
 
1437
1442
  try {
1438
- const deadline = Date.now() + timeoutMs;
1439
- while (Date.now() < deadline) {
1443
+ // Treat timeoutMs as a stall window rather than a hard runtime limit.
1444
+ // Durable events are direct progress. Once a full quiet window elapses,
1445
+ // confirm the Session is still running before renewing the wait.
1446
+ // Interaction ownership is intentionally not a liveness signal: it stays
1447
+ // active until turn/end and can therefore outlive a stalled turn.
1448
+ let lastProgressAt = Date.now();
1449
+ let lastPollSeq = tracker.lastSeq;
1450
+ while (true) {
1440
1451
  await sleep(300, signal);
1441
1452
  const history = await this.rpc(
1442
1453
  'session.history',
@@ -1450,6 +1461,9 @@ export class HarnessClient {
1450
1461
  if (!wasActive && ownership.active) ownership.reconnect?.();
1451
1462
  }
1452
1463
  const updates = tracker.consumeAll(history.events ?? []);
1464
+ const seqAdvanced = tracker.lastSeq > lastPollSeq;
1465
+ lastPollSeq = tracker.lastSeq;
1466
+ if (seqAdvanced) lastProgressAt = Date.now();
1453
1467
  if (onUpdate) {
1454
1468
  const visibleUpdates = progressMode === 'all' ? updates : updates.slice(-1);
1455
1469
  for (const update of visibleUpdates) {
@@ -1460,24 +1474,39 @@ export class HarnessClient {
1460
1474
  }
1461
1475
  }
1462
1476
  }
1463
- if (!tracker.finished) continue;
1464
- turnFinished = true;
1465
- if (!ownership?.stopRequested && !harnessTurnSucceeded(tracker.reason)) {
1477
+ if (tracker.finished) {
1478
+ turnFinished = true;
1479
+ if (!ownership?.stopRequested && !harnessTurnSucceeded(tracker.reason)) {
1480
+ throw harnessTurnError(tracker.reason);
1481
+ }
1482
+ // An accepted /stop revokes attachment delivery even when Harness
1483
+ // preserved a useful partial text answer for the existing UX.
1484
+ const artifactCount = ownership?.stopRequested
1485
+ ? 0
1486
+ : await deliverArtifacts();
1487
+ if (tracker.answer) {
1488
+ return tracker.answer;
1489
+ }
1490
+ if (artifactCount > 0) return '';
1491
+ if (ownership?.stopRequested) throw turnStoppedError();
1466
1492
  throw harnessTurnError(tracker.reason);
1467
1493
  }
1468
- // An accepted /stop revokes attachment delivery even when Harness
1469
- // preserved a useful partial text answer for the existing UX.
1470
- const artifactCount = ownership?.stopRequested
1471
- ? 0
1472
- : await deliverArtifacts();
1473
- if (tracker.answer) {
1474
- return tracker.answer;
1494
+
1495
+ if (Date.now() - lastProgressAt < timeoutMs) continue;
1496
+
1497
+ let running = false;
1498
+ try {
1499
+ running = await this.isSessionRunning(sessionId, { signal });
1500
+ } catch (error) {
1501
+ if (signal?.aborted) throw signal.reason ?? error;
1502
+ // A failed liveness probe is not evidence of progress.
1503
+ }
1504
+ if (running) {
1505
+ lastProgressAt = Date.now();
1506
+ continue;
1475
1507
  }
1476
- if (artifactCount > 0) return '';
1477
- if (ownership?.stopRequested) throw turnStoppedError();
1478
- throw harnessTurnError(tracker.reason);
1508
+ throw new HarnessTurnError('harness-reply-timeout');
1479
1509
  }
1480
- throw new HarnessTurnError('harness-reply-timeout');
1481
1510
  } catch (error) {
1482
1511
  // Once cancellation was accepted, transport/poll failures and timeouts
1483
1512
  // describe the convergence of that stop, not an unrelated ask failure.
@@ -356,4 +356,15 @@ export default {
356
356
  '⚠️ Repair verification failed: the dedicated test card could not be sent, so card.action.trigger cannot be confirmed restored. Do not authorize again; check the bot message permission and connection status first.',
357
357
  '⚠️ 修复验证中断:Runtime 已停止,未完成 card.action.trigger 实测,不能确认修复成功。请不要重复授权;先等待机器人恢复连接。':
358
358
  '⚠️ Repair verification interrupted: the Runtime stopped before the card.action.trigger test completed, so the repair cannot be confirmed. Do not authorize again; wait for the bot to reconnect.',
359
+
360
+ // feishu/bridge.mjs — interaction cards (approve/reject / answer buttons)
361
+ '该审批已处理或不存在,无需重复操作。':
362
+ 'This approval has already been processed or does not exist; no need to repeat the action.',
363
+ // feishu/feishu-cards.mjs — approval card
364
+ '操作参数:\n{operation}': 'Operation parameters:\n{operation}',
365
+ '✅ 批准': '✅ Approve',
366
+ '❌ 拒绝': '❌ Reject',
367
+ '🔐 工具审批': '🔐 Tool approval',
368
+ // feishu/feishu-cards.mjs — question card
369
+ '❓ 请补充信息{progress}': '❓ Please provide more information{progress}',
359
370
  };
@@ -123,6 +123,7 @@ export default {
123
123
  '/workspace 工作区序号或绝对路径 切换工作区':
124
124
  '/workspace <workspace index or absolute path> Switch workspace',
125
125
  '/workspacelist 列出工作区绝对路径': '/workspacelist List absolute workspace paths',
126
+ '/ws、/wsl、/workspaces 工作区命令别名': '/ws, /wsl, /workspaces Workspace command aliases',
126
127
  '/sessionlist [工作区序号或绝对路径] 列出会话 ID 和标题':
127
128
  '/sessionlist [workspace index or absolute path] List session IDs and titles',
128
129
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题':