@xmanrui/dsh-im 5.0.1 → 5.0.3

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": "5.0.1",
3
+ "version": "5.0.3",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
6
6
  "keywords": [
@@ -1,3 +1,5 @@
1
+ import { harnessPeer } from './harness-peer.mjs';
2
+
1
3
  /**
2
4
  * Adapt the Host's Typert command gateway to the channel Harness client.
3
5
  * Programmatic production fixtures may omit the gateway and exercise other assembly paths.
@@ -12,12 +14,14 @@ export function createHarnessCommandExecutor(ctx, provided) {
12
14
  if (typeof gateway.invoke !== 'function') {
13
15
  throw new TypeError('dsh-im requires a callable ctx.typertGateway');
14
16
  }
17
+ const peer = harnessPeer(ctx);
15
18
  return async (sessionId, line, options = {}) => {
16
19
  const request = {
17
20
  namespace: 'commands',
18
21
  method: 'execute',
19
22
  args: { agentId: sessionId, line, images: [] },
20
23
  signal: options.signal,
24
+ ...(peer === undefined ? {} : { peer }),
21
25
  };
22
26
  try {
23
27
  return await gateway.invoke(request);
@@ -0,0 +1,18 @@
1
+ const peers = new WeakMap();
2
+
3
+ /** One caller identity shared by the Host's session and command gateways. */
4
+ export function harnessPeer(ctx) {
5
+ const scope = ctx?.root ?? ctx;
6
+ const cached = peers.get(scope);
7
+ if (cached) return cached;
8
+ const connection = ctx?.connection;
9
+ if (typeof connection?.createPeer !== 'function') return undefined;
10
+ // IM approvals and questions have their own listeners and response routing.
11
+ const peer = connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' });
12
+ peers.set(scope, peer);
13
+ ctx.effect?.(() => () => {
14
+ if (peers.get(scope) === peer) peers.delete(scope);
15
+ return peer.dispose();
16
+ }, 'dsh-im: shared Harness caller');
17
+ return peer;
18
+ }
@@ -2,6 +2,8 @@ import { randomUUID } from 'node:crypto';
2
2
 
3
3
  import { activeHarnessInteractionOwner, clearModelCatalogCache, hasActiveHarnessInteractionOwner, harnessToolCallFromEvent, HarnessInteractionError } from '../../src/channels/shared/harness-client.mjs';
4
4
  import { extractConnectionEvidence } from '../../src/channels/shared/connection-error.mjs';
5
+ import { harnessPeer } from './harness-peer.mjs';
6
+ import { sameWorkspacePath } from '../../src/channels/shared/default-workspace.mjs';
5
7
 
6
8
  const modernApis = new WeakMap();
7
9
 
@@ -54,6 +56,12 @@ function questionError(message, code) {
54
56
  return error;
55
57
  }
56
58
 
59
+ function adoptionError(code, message) {
60
+ const error = new Error(message);
61
+ error.failure = { code, message, details: {} };
62
+ return error;
63
+ }
64
+
57
65
  function sessionEvents(session) {
58
66
  if (typeof session?.snapshotEvents === 'function') {
59
67
  const events = session.snapshotEvents();
@@ -211,9 +219,7 @@ class ModernHarnessApi {
211
219
  constructor(ctx, gateway, scope) {
212
220
  this.#gateway = gateway;
213
221
  this.#scope = scope;
214
- // New Hosts require an explicit caller. IM interactions use the adapter's
215
- // existing event listeners; this peer only owns Gateway calls and streams.
216
- this.#peer = ctx.connection?.createPeer?.({ principal: { kind: 'owner' }, interactions: 'none' });
222
+ this.#peer = harnessPeer(ctx);
217
223
 
218
224
  this.host = Object.freeze({
219
225
  describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
@@ -231,6 +237,7 @@ class ModernHarnessApi {
231
237
  create: (request, signal) => rpcResult(request, () => this.#invoke(
232
238
  'session', 'create', { request: request.payload }, signal,
233
239
  )),
240
+ adopt: (request, signal) => rpcResult(request, () => this.#adoptSession(request.payload, signal)),
234
241
  history: (request, signal) => rpcResult(request, () => this.#history(request.payload, signal)),
235
242
  prompt: (request, signal) => rpcResult(request, () => this.#invoke(
236
243
  'session',
@@ -342,6 +349,33 @@ class ModernHarnessApi {
342
349
  return frame;
343
350
  }
344
351
 
352
+ async #adoptSession({ sessionId, workspaceId, cwd }, signal) {
353
+ // Since DSH 0.2.1, create only reuses blank Sessions and can replace their
354
+ // preset. Binding must observe the exact existing identity instead; the
355
+ // next prompt resumes its Agent with the persisted configuration.
356
+ const { header } = await this.#sessionSnapshot(sessionId, 1, signal);
357
+ if (header?.id !== sessionId || typeof header.cwd !== 'string') {
358
+ throw new Error('Harness returned an invalid Session header for adoption');
359
+ }
360
+ if (header.origin !== undefined) {
361
+ throw adoptionError('session-subagent-unsupported', 'Only ordinary Sessions can be adopted');
362
+ }
363
+ let expectedCwd = cwd;
364
+ if (workspaceId !== undefined) {
365
+ const baseline = await this.#workspaceList(signal);
366
+ const workspace = baseline.items?.find(item => item.workspaceId === workspaceId);
367
+ if (cwd !== undefined || !workspace?.sessionIds?.includes(sessionId)) {
368
+ throw adoptionError('session-workspace-ambiguous', 'Session workspace membership changed during adoption');
369
+ }
370
+ expectedCwd = workspace.path;
371
+ }
372
+ if (!await sameWorkspacePath(header.cwd, expectedCwd)) {
373
+ throw adoptionError('session-workspace-ambiguous', 'Session directory does not match its workspace');
374
+ }
375
+ signal?.throwIfAborted();
376
+ return { sessionId };
377
+ }
378
+
345
379
  async #history(payload, signal) {
346
380
  const { sessionId, maxMessages = 50, beforeSeq } = payload;
347
381
  let cursor = this.#sessionCursors.get(sessionId);
@@ -871,7 +905,6 @@ class ModernHarnessApi {
871
905
  questionError('dsh-im interaction adapter was disposed', 'ASK_ABORTED'),
872
906
  );
873
907
  for (const dispose of this.#disposers.splice(0).reverse()) dispose?.();
874
- return this.#peer?.dispose();
875
908
  }
876
909
  }
877
910
 
@@ -8,6 +8,7 @@ import { dirname } from 'node:path';
8
8
  */
9
9
  const EXTENSION_KEYS = Object.freeze([
10
10
  'emailBindings', 'mailCursor', 'pendingAuth', 'threadIds', 'rootAnchors',
11
+ 'whatsappBotMessageIds',
11
12
  ]);
12
13
 
13
14
  const PENDING_MESSAGE_LIMIT = 200;
@@ -23,7 +23,7 @@ const REASONS = new Set([
23
23
  ]);
24
24
  const RESOURCES = new Set(['credential-store', 'account-config', 'account-state', 'workspace-config', 'workspace-directory']);
25
25
  const RPC_METHODS = new Set([
26
- 'host.describe', 'workspace.list', 'workspace.create', 'session.list', 'session.create',
26
+ 'host.describe', 'workspace.list', 'workspace.create', 'session.list', 'session.create', 'session.adopt',
27
27
  'session.history', 'session.prompt', 'session.rename', 'session.cancel', 'session.models',
28
28
  'session.permissions', 'session.selectModel', 'llm.models',
29
29
  ]);
@@ -1320,7 +1320,10 @@ export class HarnessClient {
1320
1320
  }
1321
1321
 
1322
1322
  async adoptWorkspaceSession(value, options = {}) {
1323
- return adoptRegisteredWorkspaceSession(this, value, options);
1323
+ // Modern Hosts separate observing an existing Session from creating one.
1324
+ // Keep the legacy transport contract for Hosts without this adapter seam.
1325
+ const method = typeof this.#apiProxy?.sessions?.adopt === 'function' ? 'session.adopt' : 'session.create';
1326
+ return adoptRegisteredWorkspaceSession(this, value, options, 30_000, method);
1324
1327
  }
1325
1328
 
1326
1329
  async isUngroupedWorkspace(workspace) {
@@ -83,7 +83,7 @@ function sessionSummary(sessionId, value) {
83
83
  return { cwd: summary.cwd, title: typeof title === 'string' ? title : null };
84
84
  }
85
85
 
86
- export async function adoptRegisteredWorkspaceSession(client, value, options = {}, timeoutMs = 30_000) {
86
+ export async function adoptRegisteredWorkspaceSession(client, value, options = {}, timeoutMs = 30_000, method = 'session.create') {
87
87
  const sessionId = validatedSessionId(value);
88
88
  await client.ensureRunning(options);
89
89
  const workspaceList = await client.rpc('workspace.list', {}, timeoutMs, options);
@@ -103,12 +103,12 @@ export async function adoptRegisteredWorkspaceSession(client, value, options = {
103
103
  if (await client.isUngroupedWorkspace?.(workspace.path)) {
104
104
  await mkdir(workspace.path, { recursive: true });
105
105
  }
106
- const adopted = await client.rpc('session.create', {
106
+ const adopted = await client.rpc(method, {
107
107
  ...(workspace.workspaceId ? { workspaceId: workspace.workspaceId } : { cwd: workspace.path }),
108
108
  sessionId,
109
109
  }, timeoutMs, options);
110
110
  if (!adopted || adopted.sessionId !== sessionId) {
111
- throw new Error('Harness returned an invalid response for session.create');
111
+ throw new Error(`Harness returned an invalid response for ${method}`);
112
112
  }
113
113
  return {
114
114
  sessionId,
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { constants as fsConstants } from 'node:fs';
3
- import { copyFile, lstat, mkdtemp, open, realpath, unlink } from 'node:fs/promises';
3
+ import { copyFile, lstat, mkdir, mkdtemp, open, realpath, unlink } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { basename, extname, isAbsolute, join, resolve } from 'node:path';
6
6
 
@@ -35,12 +35,15 @@ const artifactProviderSettlements = new WeakMap();
35
35
  let managedSnapshotDirectoryPromise;
36
36
 
37
37
  function managedSnapshotDirectory() {
38
- managedSnapshotDirectoryPromise ??= mkdtemp(join(tmpdir(), 'dsh-im-outbound-'));
38
+ managedSnapshotDirectoryPromise ??= mkdtemp(join(tmpdir(), 'dsh-im-outbound-')).catch((error) => {
39
+ managedSnapshotDirectoryPromise = undefined;
40
+ throw error;
41
+ });
39
42
  return managedSnapshotDirectoryPromise;
40
43
  }
41
44
 
42
- function artifactError(code, message) {
43
- const error = new Error(message);
45
+ function artifactError(code, message, cause) {
46
+ const error = new Error(message, cause === undefined ? undefined : { cause });
44
47
  error.code = code;
45
48
  return error;
46
49
  }
@@ -194,7 +197,17 @@ async function snapshotFile(workspace, requestedPath, signal) {
194
197
 
195
198
  const directory = await managedSnapshotDirectory();
196
199
  storagePath = join(directory, `${randomUUID()}.artifact`);
197
- await copyFile(canonicalPath, storagePath, fsConstants.COPYFILE_EXCL);
200
+ try {
201
+ await copyFile(canonicalPath, storagePath, fsConstants.COPYFILE_EXCL);
202
+ } catch (error) {
203
+ if (error?.code !== 'ENOENT') throw error;
204
+ signal?.throwIfAborted();
205
+ // System temp cleanup can remove the cached directory between sends.
206
+ // Recreate it with mkdtemp's private permissions and retry only once.
207
+ await mkdir(directory, { recursive: true, mode: 0o700 });
208
+ signal?.throwIfAborted();
209
+ await copyFile(canonicalPath, storagePath, fsConstants.COPYFILE_EXCL);
210
+ }
198
211
  signal?.throwIfAborted();
199
212
 
200
213
  const snapshot = await lstat(storagePath, { bigint: true });
@@ -214,7 +227,7 @@ async function snapshotFile(workspace, requestedPath, signal) {
214
227
  if (storagePath) await unlink(storagePath).catch(() => undefined);
215
228
  if (error?.code?.startsWith?.('artifact-')) throw error;
216
229
  if (signal?.aborted) throw signal.reason ?? error;
217
- throw artifactError('artifact-unavailable', 'The requested file is unavailable.');
230
+ throw artifactError('artifact-unavailable', 'The requested file is unavailable.', error);
218
231
  }
219
232
  }
220
233
 
@@ -24,6 +24,7 @@ import { runCompactCommand } from '../shared/compact-command.mjs';
24
24
  import { isSharedLocalCommand } from '../shared/command-permission.mjs';
25
25
  import { isClearCommand, runClearCommand } from '../shared/clear-command.mjs';
26
26
  import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
27
+ import { isPermissionCommand, runPermissionCommand } from '../shared/permission-command.mjs';
27
28
  import {
28
29
  isControlCommand,
29
30
  runControlCommand,
@@ -86,6 +87,8 @@ function helpText() {
86
87
  t('/new 开启一个全新会话'),
87
88
  t('/compact 压缩当前会话的较早上下文'),
88
89
  t('/clear 清空当前会话上下文(保留 Session 绑定和历史记录)'),
90
+ t('/permissionlist 按序号列出权限档位'),
91
+ t('/permission [序号或完整ID] 查看或切换当前会话权限'),
89
92
  t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
90
93
  t('/workspace 工作区序号或绝对路径 切换工作区'),
91
94
  t('/workspacelist 列出工作区绝对路径'),
@@ -921,7 +924,8 @@ export class WecomHarnessBridge {
921
924
  text: commandText,
922
925
  hasImages: hasInboundImages(commandMessage),
923
926
  hasFiles: hasInboundFiles(commandMessage),
924
- ...(parseWecomMenu(commandText) && !hasInboundImages(commandMessage) && !hasInboundFiles(commandMessage)
927
+ ...(isPermissionCommand(commandText)
928
+ || (parseWecomMenu(commandText) && !hasInboundImages(commandMessage) && !hasInboundFiles(commandMessage))
925
929
  ? { isCommand: true } : {}),
926
930
  });
927
931
  if (!access.allowed) {
@@ -976,6 +980,7 @@ export class WecomHarnessBridge {
976
980
  && (parseWecomMenu(commandText) || ['/help', '/status', '/new'].includes(commandText.toLowerCase())
977
981
  || this.#cardFrames.has(frame));
978
982
  const commandRunner = isClearCommand(commandText) ? runClearCommand
983
+ : isPermissionCommand(commandText) ? runPermissionCommand
979
984
  : isHistoryCommand(commandText) ? runHistoryCommand
980
985
  : hasInboundFiles(commandMessage) ? null : isControlCommand(commandText)
981
986
  ? runControlCommand
@@ -1,3 +1,36 @@
1
1
  import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
2
2
 
3
- export class WhatsappStateStore extends ConversationStateStore {}
3
+ const BOT_MESSAGE_LIMIT = 2_000;
4
+
5
+ export class WhatsappStateStore extends ConversationStateStore {
6
+ #botMessageIds = new Set();
7
+
8
+ async load() {
9
+ await super.load();
10
+ const stored = this.extensionState().whatsappBotMessageIds;
11
+ this.#botMessageIds = new Set(Array.isArray(stored)
12
+ ? stored.filter((id) => typeof id === 'string' && id).slice(-BOT_MESSAGE_LIMIT)
13
+ : []);
14
+ return this;
15
+ }
16
+
17
+ isBotMessage(jid, id) {
18
+ return typeof id === 'string' && Boolean(id) && this.#botMessageIds.has(`${jid}:${id}`);
19
+ }
20
+
21
+ async rememberBotMessage(jid, id) {
22
+ if (typeof jid !== 'string' || !jid.endsWith('@g.us')
23
+ || typeof id !== 'string' || !id || this.isBotMessage(jid, id)) return;
24
+ this.#botMessageIds.add(`${jid}:${id}`);
25
+ while (this.#botMessageIds.size > BOT_MESSAGE_LIMIT) {
26
+ this.#botMessageIds.delete(this.#botMessageIds.values().next().value);
27
+ }
28
+ this.extensionState().whatsappBotMessageIds = [...this.#botMessageIds];
29
+ await this.persist();
30
+ }
31
+
32
+ async remove() {
33
+ await super.remove();
34
+ this.#botMessageIds.clear();
35
+ }
36
+ }
@@ -311,6 +311,7 @@ function whatsappAccountMatcher(accountJid, aliases) {
311
311
  export function normalizeWhatsappMessage(message, accountJid, {
312
312
  download = downloadMediaMessage,
313
313
  accountAliases = [],
314
+ isBotMessage = () => false,
314
315
  } = {}) {
315
316
  const remoteJid = typeof message?.key?.remoteJid === 'string' ? message.key.remoteJid : '';
316
317
  const alternateRemoteJid = typeof message?.key?.remoteJidAlt === 'string'
@@ -332,8 +333,11 @@ export function normalizeWhatsappMessage(message, accountJid, {
332
333
  const context = messageContext(content);
333
334
  const mentioned = Array.isArray(context?.mentionedJid)
334
335
  && context.mentionedJid.some(matchesAccount);
335
- const replyToSelf = typeof context?.participant === 'string'
336
- && matchesAccount(context.participant);
336
+ // The linked account also sends human messages. Only a known bot message
337
+ // in this chat counts as a reply trigger, not every reply to the account.
338
+ const replyToBot = typeof context?.participant === 'string'
339
+ && matchesAccount(context.participant)
340
+ && isBotMessage(remoteJid, context.stanzaId) === true;
337
341
  const image = whatsappImageSource(message, content, download, { viewOnce });
338
342
  const file = whatsappFileSource(message, content, download);
339
343
  const replyTo = whatsappReplyReference(context);
@@ -352,7 +356,7 @@ export function normalizeWhatsappMessage(message, accountJid, {
352
356
  images: image ? [image] : [],
353
357
  files: file ? [file] : [],
354
358
  ...(replyTo ? { replyTo } : {}),
355
- addressed: !group || fromMe || mentioned || replyToSelf,
359
+ addressed: !group || mentioned || replyToBot,
356
360
  selfChat,
357
361
  replyTarget: { jid: remoteJid, quoted: message, selfChat },
358
362
  reactionTarget: { jid: remoteJid, key: message.key },
@@ -462,6 +466,7 @@ function whatsappArtifactError(error) {
462
466
  export class WhatsappBotClient {
463
467
  #socket;
464
468
  #outboundIds;
469
+ #rememberBotMessage;
465
470
  #signal;
466
471
  #abortController = new AbortController();
467
472
  #mediaUploadTimeoutMs;
@@ -473,9 +478,11 @@ export class WhatsappBotClient {
473
478
  signal,
474
479
  mediaUploadTimeoutMs = WHATSAPP_MEDIA_UPLOAD_TIMEOUT_MS,
475
480
  logger = console,
481
+ rememberBotMessage = async () => {},
476
482
  } = {}) {
477
483
  this.#socket = socket;
478
484
  this.#outboundIds = outboundIds;
485
+ this.#rememberBotMessage = rememberBotMessage;
479
486
  this.#signal = signal
480
487
  ? AbortSignal.any([signal, this.#abortController.signal])
481
488
  : this.#abortController.signal;
@@ -530,6 +537,7 @@ export class WhatsappBotClient {
530
537
  );
531
538
  const result = await waitWithSignal(pending, this.#signal);
532
539
  this.#outboundIds.remember(result?.key?.id);
540
+ await this.#rememberBotMessage(target.jid, edit?.id ?? result?.key?.id ?? messageId);
533
541
  return {
534
542
  ...result,
535
543
  key: { remoteJid: target.jid, fromMe: true, id: messageId, ...result?.key },
@@ -663,6 +671,7 @@ export class WhatsappBotClient {
663
671
  }
664
672
  this.#signal?.throwIfAborted();
665
673
  this.#outboundIds.remember(result?.key?.id);
674
+ await this.#rememberBotMessage(target.jid, result?.key?.id ?? messageId);
666
675
  return result;
667
676
  }
668
677
 
@@ -800,6 +809,7 @@ export class WhatsappRuntime {
800
809
  onMessage: async (raw, context) => {
801
810
  const linkedAccount = context?.socket?.user;
802
811
  const message = normalizeWhatsappMessage(raw, this.#config.accountJid, {
812
+ isBotMessage: (jid, id) => this.#state.isBotMessage?.(jid, id) === true,
803
813
  accountAliases: [
804
814
  linkedAccount?.id,
805
815
  linkedAccount?.lid,
@@ -838,6 +848,15 @@ export class WhatsappRuntime {
838
848
  throw new Error('WhatsApp linked account does not match the saved bot');
839
849
  }
840
850
  const client = new WhatsappBotClient(session.socket, outboundIds, {
851
+ rememberBotMessage: async (jid, id) => {
852
+ try {
853
+ await this.#state.rememberBotMessage?.(jid, id);
854
+ } catch (error) {
855
+ // Delivery already succeeded; a bookkeeping failure must not turn
856
+ // it into a failed send that can be retried and duplicated.
857
+ this.#logger.warn?.('[dsh-im:whatsapp] failed to persist bot message identity:', error);
858
+ }
859
+ },
841
860
  signal: controller.signal,
842
861
  mediaUploadTimeoutMs: this.#mediaUploadTimeoutMs,
843
862
  logger: this.#logger,