@xmanrui/dsh-im 0.11.0 → 0.12.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.
@@ -1,5 +1,9 @@
1
1
  import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
2
2
  import { runCompactCommand } from '../shared/compact-command.mjs';
3
+ import {
4
+ isControlCommand,
5
+ runControlCommand,
6
+ } from '../shared/control-command.mjs';
3
7
  import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
4
8
  import {
5
9
  harnessAnswerForQuestion,
@@ -7,6 +11,10 @@ import {
7
11
  validHarnessQuestion,
8
12
  } from '../shared/harness-question.mjs';
9
13
  import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
14
+ import {
15
+ isModelCommand,
16
+ runModelCommand,
17
+ } from '../shared/model-command.mjs';
10
18
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
11
19
  import {
12
20
  fetchImageBuffer,
@@ -38,6 +46,10 @@ const HELP_TEXT = [
38
46
  '/workspacelist 列出工作区绝对路径',
39
47
  '/sessionlist [工作区序号或绝对路径] 列出会话 ID 和标题',
40
48
  '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
49
+ '/models 列出所有可用模型',
50
+ '/model [模型ID] 查看或切换当前会话模型',
51
+ '/stop 停止当前任务',
52
+ '/steer 补充指令 纠偏当前任务',
41
53
  '/status 检查连接状态',
42
54
  '/help 显示本帮助',
43
55
  ].join('\n');
@@ -134,6 +146,7 @@ export class QqHarnessBridge {
134
146
  #interactionKeys = new Map();
135
147
  #acceptedMessageIds = new Set();
136
148
  #approvalTasks = new Set();
149
+ #commandTasks = new Set();
137
150
  #approvals;
138
151
 
139
152
  constructor({
@@ -184,6 +197,34 @@ export class QqHarnessBridge {
184
197
  rememberConnectionTestTarget(this.#state, message.replyTarget);
185
198
  }
186
199
  const pending = this.#pendingInteractions.get(key);
200
+ const commandText = safeText(message);
201
+ const commandRunner = isControlCommand(commandText)
202
+ ? runControlCommand
203
+ : (isModelCommand(commandText) ? runModelCommand : null);
204
+ const allowed = this.#ownerUserOpenid === '*' || sender === this.#ownerUserOpenid;
205
+ const addressed = message.kind !== 'group'
206
+ || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE';
207
+ if (commandRunner && allowed && addressed) {
208
+ let task;
209
+ task = this.#processFastCommand(
210
+ message,
211
+ messageId,
212
+ key,
213
+ commandText,
214
+ commandRunner,
215
+ ).catch((error) => {
216
+ if (error?.code === 'turn-stopped' || this.#signal?.aborted) return;
217
+ this.#status.lastError = error?.message ?? String(error);
218
+ this.#logger.error?.('[dsh-im:qq] failed to process a command:', error);
219
+ return this.#bot.sendText(message.replyTarget, '消息处理失败,请稍后重试。')
220
+ .catch(() => undefined);
221
+ }).finally(() => {
222
+ this.#acceptedMessageIds.delete(messageId);
223
+ this.#commandTasks.delete(task);
224
+ });
225
+ this.#commandTasks.add(task);
226
+ return task;
227
+ }
187
228
  const approval = this.#approvals.claimReply({
188
229
  key,
189
230
  actor: sender,
@@ -262,9 +303,35 @@ export class QqHarnessBridge {
262
303
  pending.queue ? [pending.queue] : []
263
304
  )),
264
305
  ...this.#approvalTasks,
306
+ ...this.#commandTasks,
265
307
  ]);
266
308
  }
267
309
 
310
+ async #processFastCommand(message, messageId, key, text, runner) {
311
+ this.#signal?.throwIfAborted();
312
+ if (this.#state.hasSeen(messageId)) return;
313
+ await this.#state.markSeen(messageId);
314
+ this.#status.messagesReceived += 1;
315
+ this.#status.lastMessageAt = new Date().toISOString();
316
+ const result = await runner(text, this.#harness, this.#state, key, {
317
+ signal: this.#signal,
318
+ hasImages: hasQqImageAttachments(message),
319
+ pendingInteraction: this.#pendingInteractions.has(key)
320
+ || this.#approvals.hasPending(key),
321
+ control: { owner: this, key },
322
+ });
323
+ if (result?.stopped) {
324
+ await Promise.allSettled([
325
+ this.#cancelPendingInteraction(key),
326
+ this.#approvals.closeRoute(key),
327
+ ]);
328
+ }
329
+ for (const reply of result?.messages ?? [result?.message]) {
330
+ if (reply) await this.#bot.sendText(message.replyTarget, reply);
331
+ }
332
+ this.#status.lastError = null;
333
+ }
334
+
268
335
  async #process(message, key, { alreadyRecorded = false } = {}) {
269
336
  if (this.#signal?.aborted) return;
270
337
  const messageId = nonEmptyString(message?.messageId);
@@ -360,6 +427,7 @@ export class QqHarnessBridge {
360
427
  askOptions: {
361
428
  timeoutMs: this.#replyTimeoutMs,
362
429
  signal: this.#signal,
430
+ control: { owner: this, key },
363
431
  onUpdate: stream ? async (update) => {
364
432
  const progress = update.type === 'text'
365
433
  ? update.text
@@ -399,6 +467,22 @@ export class QqHarnessBridge {
399
467
  this.#status.lastReplyAt = new Date().toISOString();
400
468
  this.#status.lastError = null;
401
469
  } catch (error) {
470
+ if (error?.code === 'turn-stopped') {
471
+ if (stream) {
472
+ try {
473
+ await stream.cancel?.();
474
+ } catch (streamError) {
475
+ this.#logger.warn?.('[dsh-im:qq] unable to cancel a stopped QQ stream:', streamError);
476
+ }
477
+ try {
478
+ await this.#bot.sendText(target, '已停止。');
479
+ } catch (sendError) {
480
+ this.#logger.warn?.('[dsh-im:qq] unable to announce a stopped QQ turn:', sendError);
481
+ }
482
+ }
483
+ await this.#state.markSeen(messageId);
484
+ return;
485
+ }
402
486
  stream?.cancel?.();
403
487
  if (this.#signal?.aborted) return;
404
488
  this.#status.lastError = error?.message ?? String(error);
@@ -511,7 +511,9 @@ export function createBotWorkspaceScope(harness, { botId, workspaces, state }) {
511
511
  }
512
512
  };
513
513
  }
514
- if ((property === 'listWorkspaces' || property === 'listWorkspaceSessions')
514
+ if ((property === 'listWorkspaces'
515
+ || property === 'listWorkspaceSessions'
516
+ || property === 'listModels')
515
517
  && typeof target[property] === 'function') {
516
518
  return async (...args) => {
517
519
  if (!isCurrentScope()) {
@@ -627,6 +629,30 @@ export function createBotWorkspaceScope(harness, { botId, workspaces, state }) {
627
629
  sessionGenerations.delete(sessionId);
628
630
  const isCurrentSession = () => isCurrentScope()
629
631
  && generation === workspaces.generationFor(botId);
632
+ const invokeCurrentSession = async (method, args, action) => {
633
+ if (!isCurrentSession()) {
634
+ throw workspaceSessionStale(
635
+ `The bot workspace changed before this ${action} started.`,
636
+ );
637
+ }
638
+ const result = await target[method](sessionId, ...args);
639
+ if (!isCurrentSession()) {
640
+ throw workspaceSessionStale(
641
+ `The bot workspace changed while this ${action} was running.`,
642
+ );
643
+ }
644
+ return result;
645
+ };
646
+ const invokeStartedSessionMutation = async (method, args, action) => {
647
+ if (!isCurrentSession()) {
648
+ throw workspaceSessionStale(
649
+ `The bot workspace changed before this ${action} started.`,
650
+ );
651
+ }
652
+ // Once an irreversible control mutation has started, preserve its
653
+ // actual outcome even if a workspace switch commits concurrently.
654
+ return target[method](sessionId, ...args);
655
+ };
630
656
  return Object.freeze({
631
657
  sessionId,
632
658
  async sessionExists(...args) {
@@ -634,6 +660,24 @@ export function createBotWorkspaceScope(harness, { botId, workspaces, state }) {
634
660
  const exists = await target.sessionExists(sessionId, ...args);
635
661
  return isCurrentSession() && exists;
636
662
  },
663
+ models(...args) {
664
+ return invokeCurrentSession('getSessionModels', args, 'model listing');
665
+ },
666
+ selectModel(...args) {
667
+ return invokeCurrentSession('selectSessionModel', args, 'model selection');
668
+ },
669
+ isRunning(...args) {
670
+ return invokeCurrentSession('isSessionRunning', args, 'run-state check');
671
+ },
672
+ hasActiveTurn(...args) {
673
+ return invokeCurrentSession('hasActiveTurn', args, 'turn ownership check');
674
+ },
675
+ stopActiveTurn(...args) {
676
+ return invokeStartedSessionMutation('stopActiveTurn', args, 'turn stop');
677
+ },
678
+ steerActiveTurn(...args) {
679
+ return invokeStartedSessionMutation('steerActiveTurn', args, 'turn steering');
680
+ },
637
681
  ask(...args) {
638
682
  if (!isCurrentSession()) {
639
683
  throw workspaceSessionStale(
@@ -0,0 +1,84 @@
1
+ const CONTROL_COMMAND = /^\/(?:stop|steer)(?=$|\s)/iu;
2
+ const STOP_COMMAND = /^\/stop(?=$|\s)/iu;
3
+ const STOP_USAGE = '用法:/stop(不带参数)';
4
+ const STEER_USAGE = '用法:/steer <补充指令>';
5
+ const TEXT_ONLY = '控制命令仅支持纯文字,请移除图片后重试。';
6
+
7
+ function commandResult(message, extra = {}) {
8
+ return { message, ...extra };
9
+ }
10
+
11
+ function requestOptions(signal) {
12
+ return signal ? { signal } : {};
13
+ }
14
+
15
+ function boundSession(harness, state, key) {
16
+ if (typeof state?.sessionFor !== 'function') return null;
17
+ const sessionId = state.sessionFor(key);
18
+ if (typeof sessionId !== 'string' || !sessionId) return null;
19
+ if (typeof harness?.workspaceSession !== 'function') {
20
+ throw new TypeError('Harness does not support workspace sessions');
21
+ }
22
+ const session = harness.workspaceSession(sessionId);
23
+ if (!session || typeof session !== 'object') {
24
+ throw new TypeError('Harness returned an invalid workspace session');
25
+ }
26
+ return session;
27
+ }
28
+
29
+ export function isControlCommand(text) {
30
+ return typeof text === 'string' && CONTROL_COMMAND.test(text.trim());
31
+ }
32
+
33
+ export async function runControlCommand(text, harness, state, key, {
34
+ signal,
35
+ hasImages = false,
36
+ pendingInteraction = false,
37
+ control,
38
+ } = {}) {
39
+ if (!isControlCommand(text)) return null;
40
+ const command = text.trim();
41
+ const stop = STOP_COMMAND.test(command);
42
+
43
+ if (hasImages) return commandResult(TEXT_ONLY);
44
+
45
+ if (stop) {
46
+ if (!/^\/stop$/iu.test(command)) return commandResult(STOP_USAGE);
47
+ const session = boundSession(harness, state, key);
48
+ if (!session) return commandResult('当前聊天没有正在运行的任务。');
49
+ if (typeof session.stopActiveTurn !== 'function') {
50
+ throw new TypeError('Harness session does not support stopping active turns');
51
+ }
52
+ const stopped = await session.stopActiveTurn(control, requestOptions(signal));
53
+ return stopped
54
+ ? commandResult('已请求停止当前任务。', { stopped: true })
55
+ : commandResult('当前聊天没有正在运行的任务。');
56
+ }
57
+
58
+ const match = /^\/steer(?:\s+([\s\S]*))?$/iu.exec(command);
59
+ const instruction = match?.[1]?.trim() ?? '';
60
+ if (!instruction) return commandResult(STEER_USAGE);
61
+ if (pendingInteraction) {
62
+ return commandResult([
63
+ '当前任务正在等待你的回答或审批。',
64
+ '',
65
+ '请先处理当前请求,或者发送 /stop 停止任务。',
66
+ ].join('\n'));
67
+ }
68
+
69
+ const session = boundSession(harness, state, key);
70
+ if (!session) {
71
+ return commandResult('当前聊天没有正在运行的任务,请直接发送普通消息。');
72
+ }
73
+ if (typeof session.steerActiveTurn !== 'function') {
74
+ throw new TypeError('Harness session does not support steering active turns');
75
+ }
76
+ const steered = await session.steerActiveTurn(
77
+ instruction,
78
+ control,
79
+ requestOptions(signal),
80
+ );
81
+ return steered
82
+ ? commandResult('已提交补充指令,Agent 会在下一步读取。')
83
+ : commandResult('当前聊天没有正在运行的任务,请直接发送普通消息。');
84
+ }
@@ -110,6 +110,10 @@ export class HarnessApprovalQueue {
110
110
  this.#logger = logger;
111
111
  }
112
112
 
113
+ hasPending(key) {
114
+ return this.#routes.get(key)?.items.some((pending) => !pending.inactive) === true;
115
+ }
116
+
113
117
  claimReply({
114
118
  key,
115
119
  actor,