@xmanrui/dsh-im 5.9.1 → 5.11.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 (135) hide show
  1. package/PROACTIVE_DELIVERY.en.md +33 -9
  2. package/PROACTIVE_DELIVERY.md +33 -9
  3. package/README.en.md +42 -7
  4. package/README.md +46 -8
  5. package/bin/dsh-im.mjs +65 -0
  6. package/docs/client-integration.md +4 -0
  7. package/lib/client.js +1735 -203
  8. package/lib/index.js +367 -341
  9. package/package.json +7 -6
  10. package/plugin-src/client/access-policy-settings.js +210 -12
  11. package/plugin-src/client/bot-general-settings.js +44 -3
  12. package/plugin-src/client/delivery-settings.js +2 -0
  13. package/plugin-src/client/delivery-sync-settings.js +269 -0
  14. package/plugin-src/client/global-settings.js +45 -7
  15. package/plugin-src/client/i18n-ru.js +112 -0
  16. package/plugin-src/client/i18n.js +110 -0
  17. package/plugin-src/client/im-channels.js +419 -0
  18. package/plugin-src/client/index.js +50 -2
  19. package/plugin-src/client/model-setting.js +6 -3
  20. package/plugin-src/client/styles.js +23 -7
  21. package/plugin-src/client/update-panel.js +2 -1
  22. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  23. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  24. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/feishu/production.mjs +50 -37
  26. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  27. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  28. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  29. package/plugin-src/host/channels/qq/production.mjs +30 -11
  30. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  31. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  32. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  33. package/plugin-src/host/channels/shared/production.mjs +14 -1
  34. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  35. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  36. package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
  37. package/plugin-src/host/channels/slack/production.mjs +28 -10
  38. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  39. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  40. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  41. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  42. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  43. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  44. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  45. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  46. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  47. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  48. package/plugin-src/host/delivery-adapter.mjs +35 -20
  49. package/plugin-src/host/delivery-service.mjs +99 -1
  50. package/plugin-src/host/delivery-suggestions.mjs +31 -1
  51. package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
  52. package/plugin-src/host/harness-connection.mjs +2 -1
  53. package/plugin-src/host/harness-peer.mjs +3 -1
  54. package/plugin-src/host/host-language-rpc.mjs +16 -2
  55. package/plugin-src/host/host-language.mjs +29 -0
  56. package/plugin-src/host/index.mjs +30 -1
  57. package/plugin-src/host/modern-harness-api.mjs +5 -1
  58. package/plugin-src/host/root-scope.mjs +32 -0
  59. package/plugin-src/host/session-sync-coordinator.mjs +290 -122
  60. package/plugin-src/host/session-sync-targets.mjs +71 -0
  61. package/plugin-src/management-rpc.mjs +18 -2
  62. package/scripts/verify-package.mjs +48 -10
  63. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  64. package/src/channels/dingtalk/state-store.mjs +56 -0
  65. package/src/channels/discord/discord-api.mjs +2 -1
  66. package/src/channels/feishu/bridge.mjs +154 -58
  67. package/src/channels/feishu/feishu-cards.mjs +10 -4
  68. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  69. package/src/channels/feishu/message-utils.mjs +106 -30
  70. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  71. package/src/channels/feishu/state-store.mjs +14 -0
  72. package/src/channels/matrix/matrix-api.mjs +2 -1
  73. package/src/channels/qq/qq-bridge.mjs +114 -14
  74. package/src/channels/qq/state-store.mjs +55 -1
  75. package/src/channels/shared/access-policy.mjs +60 -7
  76. package/src/channels/shared/action-card.mjs +83 -7
  77. package/src/channels/shared/bot-workspace-store.mjs +255 -11
  78. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  79. package/src/channels/shared/channel-capabilities.mjs +44 -0
  80. package/src/channels/shared/command-catalog.mjs +68 -3
  81. package/src/channels/shared/command-permission.mjs +6 -2
  82. package/src/channels/shared/conversation-state-store.mjs +16 -0
  83. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  84. package/src/channels/shared/deferred-delivery.mjs +4 -0
  85. package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
  86. package/src/channels/shared/delivery-sync-settings.mjs +122 -0
  87. package/src/channels/shared/diagnostic-details.mjs +6 -1
  88. package/src/channels/shared/failure-log-file.mjs +79 -0
  89. package/src/channels/shared/harness-client.mjs +259 -96
  90. package/src/channels/shared/i18n-en/diagnostics.mjs +1 -0
  91. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  92. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  93. package/src/channels/shared/i18n-en/shared-b.mjs +73 -4
  94. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  95. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  96. package/src/channels/shared/i18n-en.mjs +2 -0
  97. package/src/channels/shared/i18n-ru/diagnostics.mjs +1 -0
  98. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  99. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  100. package/src/channels/shared/i18n-ru/shared-b.mjs +72 -4
  101. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  102. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  103. package/src/channels/shared/i18n-ru.mjs +2 -0
  104. package/src/channels/shared/inbound-access.mjs +10 -0
  105. package/src/channels/shared/interface-language-store.mjs +49 -10
  106. package/src/channels/shared/interface-language.mjs +19 -1
  107. package/src/channels/shared/markdown-chunks.mjs +5 -0
  108. package/src/channels/shared/message-failure.mjs +22 -1
  109. package/src/channels/shared/model-setting.mjs +6 -3
  110. package/src/channels/shared/new-command.mjs +158 -4
  111. package/src/channels/shared/plan-goal-command.mjs +132 -0
  112. package/src/channels/shared/qrcode.mjs +5 -0
  113. package/src/channels/shared/reply-content.mjs +102 -0
  114. package/src/channels/shared/reset-command.mjs +46 -0
  115. package/src/channels/shared/semantic/artifact.mjs +133 -29
  116. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  117. package/src/channels/shared/session-nav-command.mjs +999 -0
  118. package/src/channels/shared/session-ring-support.mjs +184 -0
  119. package/src/channels/shared/session-ring.mjs +202 -0
  120. package/src/channels/shared/session-title.mjs +11 -0
  121. package/src/channels/shared/status-command.mjs +2 -1
  122. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  123. package/src/channels/shared/workspace-command.mjs +567 -31
  124. package/src/channels/shared/workspace-session.mjs +52 -4
  125. package/src/channels/slack/slack-api.mjs +2 -1
  126. package/src/channels/telegram/config-store.mjs +10 -2
  127. package/src/channels/telegram/telegram-api.mjs +19 -1
  128. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  129. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  130. package/src/channels/wecom/state-store.mjs +13 -1
  131. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  132. package/src/channels/wecom-app/state-store.mjs +13 -1
  133. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  134. package/src/channels/weixin/state-store.mjs +13 -1
  135. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -44,6 +44,9 @@ export class InterfaceLanguageStore {
44
44
  // Whether the document on disk is known to already say what #tag says. False
45
45
  // for a missing or unreadable document, so the next report repairs it.
46
46
  #stored = false;
47
+ // Language the reader picked for the plugin's own chat messages; null means
48
+ // "follow DSH" and leaves the resolution to the layers below.
49
+ #explicit = null;
47
50
 
48
51
  constructor(path) {
49
52
  if (typeof path !== 'string' || !path) {
@@ -60,12 +63,14 @@ export class InterfaceLanguageStore {
60
63
  if (error?.code !== 'ENOENT') throw error;
61
64
  this.#tag = null;
62
65
  this.#stored = false;
66
+ this.#explicit = null;
63
67
  await this.#removeStaleTemporaries();
64
68
  return this;
65
69
  }
66
- const read = this.#readTag(raw);
67
- this.#tag = read === undefined ? null : read;
70
+ const read = this.#readDocument(raw);
71
+ this.#tag = read?.mirror ?? null;
68
72
  this.#stored = read !== undefined;
73
+ this.#explicit = read?.explicit ?? null;
69
74
  await this.#removeStaleTemporaries();
70
75
  return this;
71
76
  }
@@ -85,9 +90,9 @@ export class InterfaceLanguageStore {
85
90
  }
86
91
  }
87
92
 
88
- // Returns the mirrored tag (null when the document mirrors nothing), or
93
+ // Returns both stored tags (null where the document stores nothing), or
89
94
  // undefined when the document is damaged or from an unknown future version.
90
- #readTag(raw) {
95
+ #readDocument(raw) {
91
96
  let document;
92
97
  try {
93
98
  document = JSON.parse(raw);
@@ -96,8 +101,24 @@ export class InterfaceLanguageStore {
96
101
  }
97
102
  if (!document || typeof document !== 'object' || Array.isArray(document)) return undefined;
98
103
  if (document.version !== DOCUMENT_VERSION) return undefined;
99
- if (document.interfaceLanguage === undefined) return null;
100
- return normalizeInterfaceLanguageTag(document.interfaceLanguage) ?? undefined;
104
+ return {
105
+ mirror: document.interfaceLanguage === undefined
106
+ ? null
107
+ : normalizeInterfaceLanguageTag(document.interfaceLanguage) ?? null,
108
+ explicit: document.explicitLanguage === undefined
109
+ ? null
110
+ : normalizeInterfaceLanguageTag(document.explicitLanguage) ?? null,
111
+ };
112
+ }
113
+
114
+ // Both selections live in one document, so every write repeats whichever one
115
+ // is not changing instead of dropping it.
116
+ async #write() {
117
+ await writeSettingsDocument(this.#path, {
118
+ version: DOCUMENT_VERSION,
119
+ ...(this.#explicit === null ? {} : { explicitLanguage: this.#explicit }),
120
+ ...(this.#tag === null ? {} : { interfaceLanguage: this.#tag }),
121
+ });
101
122
  }
102
123
 
103
124
  getLanguageTag() {
@@ -116,11 +137,29 @@ export class InterfaceLanguageStore {
116
137
  : normalizeInterfaceLanguageTag(value);
117
138
  if (tag === null && value !== null && value !== undefined) throw invalidTagError();
118
139
  if (tag === this.#tag && this.#stored) return tag;
119
- await writeSettingsDocument(this.#path, {
120
- version: DOCUMENT_VERSION,
121
- ...(tag === null ? {} : { interfaceLanguage: tag }),
122
- });
123
140
  this.#tag = tag;
141
+ await this.#write();
142
+ this.#stored = true;
143
+ return tag;
144
+ }
145
+
146
+ getExplicitTag() {
147
+ return this.#explicit;
148
+ }
149
+
150
+ /**
151
+ * Record the language the reader picked for the plugin's own chat messages.
152
+ * Passing null clears the explicit selection, returning resolution to DSH and
153
+ * the mirror.
154
+ */
155
+ async setExplicitTag(value) {
156
+ const tag = value === null || value === undefined
157
+ ? null
158
+ : normalizeInterfaceLanguageTag(value);
159
+ if (tag === null && value !== null && value !== undefined) throw invalidTagError();
160
+ if (tag === this.#explicit) return tag;
161
+ this.#explicit = tag;
162
+ await this.#write();
124
163
  this.#stored = true;
125
164
  return tag;
126
165
  }
@@ -16,6 +16,9 @@ const LANGUAGE_TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/u;
16
16
  * - `config`: the plugin's own `language` option (or `DSH_IM_LANGUAGE`). An
17
17
  * operator who pinned a language in the Host composition keeps it, whatever
18
18
  * any individual browser reads the interface in.
19
+ * - `explicit`: the language a reader picked for the plugin's own chat messages
20
+ * in the settings page ("settings.language.set"). It outranks what DSH is set
21
+ * to, because a reader may want English DSH with Russian bot messages.
19
22
  * - `settings`: the explicit selection in DSH's Language row, read from the
20
23
  * Host user-settings document. This is the setting users mean by "DSH is set
21
24
  * to English".
@@ -24,7 +27,22 @@ const LANGUAGE_TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/u;
24
27
  * language list, so without this layer a reader who never opened the
25
28
  * Language row would still be answered in Chinese.
26
29
  */
27
- export const HOST_LANGUAGE_SOURCES = Object.freeze(['config', 'settings', 'mirror']);
30
+ export const HOST_LANGUAGE_SOURCES = Object.freeze(['config', 'explicit', 'settings', 'mirror']);
31
+
32
+ /** Languages the plugin ships chat-message dictionaries for. */
33
+ export const MESSAGE_LANGUAGE_TAGS = Object.freeze(['zh', 'en', 'ru']);
34
+
35
+ /**
36
+ * Normalize one choice of the plugin's own message language: `'auto'` (follow
37
+ * DSH) or one of MESSAGE_LANGUAGE_TAGS. Anything else returns null, which the
38
+ * RPC layer rejects and the settings page keeps from being saved.
39
+ */
40
+ export function normalizeMessageLanguageChoice(value) {
41
+ if (typeof value !== 'string') return null;
42
+ const trimmed = value.trim();
43
+ if (trimmed === 'auto') return 'auto';
44
+ return MESSAGE_LANGUAGE_TAGS.includes(trimmed) ? trimmed : null;
45
+ }
28
46
 
29
47
  /**
30
48
  * Normalize one interface-language tag. Surrounding whitespace is trimmed;
@@ -47,6 +47,11 @@ function safeCodeFence(text, info) {
47
47
  return backticks.length <= tildes.length ? backticks : tildes;
48
48
  }
49
49
 
50
+ // Exposed for callers that fence arbitrary, untrusted text verbatim (e.g. the
51
+ // /tail export): pick a delimiter longer than any leading run in the body, so
52
+ // the body can never close its own fence.
53
+ export { longestLeadingRun, safeCodeFence };
54
+
50
55
  function removeFenceIndent(line, indent) {
51
56
  let index = 0;
52
57
  let column = 0;
@@ -23,7 +23,18 @@ const PROVIDER_FAILURES = Object.freeze({
23
23
  MALFORMED_RESPONSE: 'MODEL_STREAM',
24
24
  EMPTY_RESPONSE: 'MODEL_EMPTY_REPLY',
25
25
  CONTENT_FILTER: 'MODEL_CONTENT_REJECTED',
26
+ CONTENT_REFUSED: 'MODEL_CONTENT_REJECTED',
26
27
  UNSUPPORTED_CONTENT: 'MODEL_CONFIG',
28
+ // Codes DSH reports when a turn failed inside the model provider. These
29
+ // three were missing from the table, so the most common provider failures
30
+ // reached the user as the generic "the cause is unknown" notice: an
31
+ // exhausted balance (ACCOUNT_QUOTA), a provider error the provider itself
32
+ // did not name (PI_AI_ERROR) and a rejected request (INVALID_REQUEST, for
33
+ // example a 413 or a model on cooldown). Each one now names its cause and
34
+ // the way out.
35
+ ACCOUNT_QUOTA: 'MODEL_QUOTA',
36
+ PI_AI_ERROR: 'MODEL_SERVICE',
37
+ INVALID_REQUEST: 'MODEL_REQUEST_REJECTED',
27
38
  });
28
39
 
29
40
  // 提交超时(stage=prompt.submit 且 harness-timeout)单列文案:与「已提交、结果
@@ -66,6 +77,8 @@ const FAILURE_MESSAGES = Object.freeze({
66
77
  '暂时无法连接模型服务,本次任务未完成。请稍后重试。',
67
78
  MODEL_SERVICE:
68
79
  '模型服务暂时异常,本次任务未完成。请稍后重试。',
80
+ MODEL_REQUEST_REJECTED:
81
+ '模型请求被服务拒绝(可能是上下文过长或该模型当前不可用)。请发送 /compact 或 /new 后重试,或改用其他模型。',
69
82
  MODEL_STREAM:
70
83
  '模型回复中断或格式异常,本次任务未完成。请重试。',
71
84
  MODEL_EMPTY_REPLY:
@@ -114,7 +127,15 @@ function providerFailureCode(error) {
114
127
  if (error?.code !== 'harness-turn-failed') return null;
115
128
  const value = error?.providerCode ?? error?.details?.providerCode;
116
129
  if (typeof value !== 'string') return null;
117
- return PROVIDER_FAILURES[value.trim().toUpperCase()] ?? null;
130
+ const key = value.trim().toUpperCase();
131
+ // DSH before 0.2.3 reports DeepSeek's content-safety `refusal` stop reason as
132
+ // MALFORMED_RESPONSE. Only a message that actually names the refusal becomes a
133
+ // content rejection; genuine stream/format failures keep MODEL_STREAM.
134
+ if (key === 'MALFORMED_RESPONSE') {
135
+ const detail = `${error?.message ?? ''} ${error?.details?.message ?? ''}`;
136
+ if (/stop reason refusal/i.test(detail)) return 'MODEL_CONTENT_REJECTED';
137
+ }
138
+ return PROVIDER_FAILURES[key] ?? null;
118
139
  }
119
140
 
120
141
  function failureCode(error, details) {
@@ -135,11 +135,14 @@ export function modelCatalogHas(catalog, selection) {
135
135
  return modelCatalogEntry(catalog, selection) !== undefined;
136
136
  }
137
137
 
138
- export async function listModelCatalog(harness, options = {}) {
138
+ export async function listModelCatalog(harness, { throwOnError = false, ...options } = {}) {
139
139
  try {
140
- if (typeof harness?.listModels !== 'function') return normalizeModelCatalog(null);
140
+ if (typeof harness?.listModels !== 'function') throw new Error('Harness model catalog is unavailable');
141
141
  return normalizeModelCatalog(await harness.listModels(options));
142
- } catch {
142
+ } catch (error) {
143
+ // Status reads may degrade; save validation must distinguish a failed read
144
+ // from a successful catalog that no longer contains the selected model.
145
+ if (throwOnError) throw error;
143
146
  return normalizeModelCatalog(null);
144
147
  }
145
148
  }
@@ -1,7 +1,161 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
1
3
  import { t } from './i18n.mjs';
4
+ import { normalizeSessionTitle } from './session-title.mjs';
5
+ import { renderSessionNumber } from './session-nav-command.mjs';
6
+ import {
7
+ sessionRingEntryByNumber,
8
+ sessionRingEntryBySessionId,
9
+ } from './session-ring.mjs';
10
+
11
+ const NEW_COMMAND = /^\/new(?=$|\s)/iu;
12
+
13
+ /** Whether `text` is a /new command, with or without an inline title. */
14
+ export function isNewCommand(text) {
15
+ return typeof text === 'string' && NEW_COMMAND.test(text.trim());
16
+ }
17
+
18
+ /** The normalized inline title of `/new <title>`, or null when none/empty. */
19
+ export function newCommandTitle(text) {
20
+ if (typeof text !== 'string') return null;
21
+ const rest = text.trim().replace(/^\/new/iu, '').trim();
22
+ return normalizeSessionTitle(rest);
23
+ }
24
+
25
+ async function renameCreatedSession(harness, key, sessionId, title) {
26
+ const session = typeof harness?.workspaceSession === 'function'
27
+ ? harness.workspaceSession(sessionId, key)
28
+ : null;
29
+ if (session && typeof session.renameTitle === 'function') {
30
+ await session.renameTitle(title);
31
+ return true;
32
+ }
33
+ if (typeof harness?.renameSession === 'function') {
34
+ await harness.renameSession(sessionId, title);
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+
40
+ /**
41
+ * Create and bind a fresh Session through the conversation-level path (bot
42
+ * model, agent preset, workspace, and the pre-bind when the id must be known
43
+ * before creation). On a create/bind failure the previous binding is restored
44
+ * (never cleared) and `failed: true` is returned.
45
+ */
46
+ async function createAndBindSession(state, harness, key) {
47
+ const directory = await harness.prepareConversationDirectory?.(key, { explicitNew: true });
48
+ const warning = directory?.warning ? t(directory.warning) : null;
49
+ // A Harness without createSession keeps the old lazy path: clear the binding
50
+ // and let the next message create the Session. No eager side effects.
51
+ if (typeof harness?.createSession !== 'function') {
52
+ await state.clearSession(key);
53
+ return { sessionId: null, warning, failed: false, previousSessionId: null };
54
+ }
55
+ const previousSessionId = state.sessionFor?.(key) ?? null;
56
+ const plannedSessionId = harness?.canChooseSessionId === true ? `session-${randomUUID()}` : null;
57
+ let sessionId = null;
58
+ try {
59
+ if (plannedSessionId !== null && await state.setSession(key, plannedSessionId) === false) {
60
+ throw new Error('the conversation refused to pre-bind the new Session');
61
+ }
62
+ sessionId = await harness.createSession({
63
+ conversationKey: key,
64
+ ...(plannedSessionId === null ? {} : { sessionId: plannedSessionId }),
65
+ });
66
+ if (typeof sessionId !== 'string' || !sessionId) {
67
+ throw new TypeError('createSession returned no session id');
68
+ }
69
+ if (sessionId !== plannedSessionId && await state.setSession(key, sessionId) === false) {
70
+ throw new Error('the conversation refused to bind the new Session');
71
+ }
72
+ } catch (error) {
73
+ console.warn('[dsh-im] unable to eagerly create the new Session:', error?.message ?? error);
74
+ // Only a pre-bound id needs restoring; a plain create failure never touched
75
+ // the binding, and the previous session (or none) must stay bound.
76
+ if (plannedSessionId !== null) {
77
+ if (previousSessionId === null) await state.clearSession?.(key);
78
+ else await state.setSession?.(key, previousSessionId);
79
+ }
80
+ return { sessionId: null, warning, failed: true, previousSessionId };
81
+ }
82
+ return { sessionId, warning, failed: false, previousSessionId };
83
+ }
84
+
85
+ /**
86
+ * Eagerly create and bind the next Session for a conversation, appending a new
87
+ * ring entry. An inline `title` is applied immediately and marked user-titled.
88
+ * A create/bind failure returns `failed: true`; ring recording and the inline
89
+ * rename are best-effort and never fail the command.
90
+ */
91
+ export async function createConversationSession({ state, harness, key, title = null }) {
92
+ const { sessionId, warning, failed } = await createAndBindSession(state, harness, key);
93
+ if (failed || sessionId === null) {
94
+ return { sessionId: null, entry: null, warning, failed };
95
+ }
96
+ let entry = null;
97
+ try {
98
+ const result = await state.ensureSessionRing?.(key, sessionId, {
99
+ title: typeof title === 'string' && title ? title : undefined,
100
+ });
101
+ entry = result?.entry ?? null;
102
+ if (entry) {
103
+ await state.appendRing?.(key, entry.n);
104
+ if (typeof title === 'string' && title) {
105
+ await renameCreatedSession(harness, key, sessionId, title);
106
+ await state.markSessionRingUserTitled?.(key, entry.n);
107
+ }
108
+ }
109
+ } catch (error) {
110
+ console.warn('[dsh-im] unable to record or rename the new Session:', error?.message ?? error);
111
+ }
112
+ return { sessionId, entry, warning, failed: false };
113
+ }
114
+
115
+ /**
116
+ * /reset: create a fresh Session and swap it into the current ring entry in
117
+ * place, so the number, title and user-titled flag survive and /ls does not
118
+ * grow. With no current entry it behaves like /new (first entry). Returns
119
+ * `previousSessionId` so the reply can name the Session that left the ring.
120
+ */
121
+ export async function replaceConversationSession({ state, harness, key }) {
122
+ const ring = state?.ringFor?.(key);
123
+ const currentSessionId = state?.sessionFor?.(key) ?? null;
124
+ const currentEntry = currentSessionId && ring
125
+ ? sessionRingEntryBySessionId(ring, currentSessionId)
126
+ : null;
127
+ if (!currentEntry) {
128
+ return createConversationSession({ state, harness, key });
129
+ }
130
+ const { sessionId, warning, failed } = await createAndBindSession(state, harness, key);
131
+ if (failed || sessionId === null) {
132
+ return { sessionId: null, entry: null, warning, failed: true, previousSessionId: currentSessionId };
133
+ }
134
+ try {
135
+ await state.replaceSessionRing?.(key, currentEntry.n, sessionId);
136
+ if (typeof currentEntry.title === 'string' && currentEntry.title) {
137
+ await renameCreatedSession(harness, key, sessionId, currentEntry.title);
138
+ }
139
+ } catch (error) {
140
+ console.warn('[dsh-im] unable to replace the ring entry for /reset:', error?.message ?? error);
141
+ }
142
+ const after = state?.ringFor?.(key);
143
+ const entry = after ? sessionRingEntryByNumber(after, currentEntry.n) : null;
144
+ return { sessionId, entry, warning, failed: false, previousSessionId: currentSessionId };
145
+ }
2
146
 
3
- export async function startNewConversation({ state, harness, key }) {
4
- const result = await harness.prepareConversationDirectory?.(key, { explicitNew: true });
5
- await state.clearSession(key);
6
- return [t('已开启全新 Harness 会话。'), result?.warning ? t(result.warning) : null].filter(Boolean).join('\n');
147
+ export async function startNewConversation({ state, harness, key, title = null }) {
148
+ const { entry, warning, failed } = await createConversationSession({ state, harness, key, title });
149
+ if (failed) {
150
+ return [t('暂时无法创建新会话,请稍后重试。'), warning].filter(Boolean).join('\n');
151
+ }
152
+ const parts = [t('已开启全新 Harness 会话。')];
153
+ if (typeof title === 'string' && title && entry) {
154
+ parts.push(t('会话 {n}:{title}', {
155
+ n: renderSessionNumber(entry, { currentSessionId: entry.sessionId }),
156
+ title: entry.title || t('无标题'),
157
+ }));
158
+ }
159
+ if (warning) parts.push(warning);
160
+ return parts.join('\n');
7
161
  }
@@ -0,0 +1,132 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
2
+ import { t } from './i18n.mjs';
3
+ import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
4
+
5
+ // Session-scoped Host commands that are not part of the shared bot command
6
+ // table. The plugin does not implement them; it delegates the full command
7
+ // line to the DSH Host command gateway, exactly like /compact and /clear:
8
+ // /plan enter plan mode (optionally with a steering message)
9
+ // /plan off leave plan mode
10
+ // /goal view the current goal / available subcommands
11
+ // /goal <...> set, edit, clear, pause or resume the goal
12
+ // When the Host has not registered a command the gateway result is undefined
13
+ // and the user gets a "not registered" notice instead of a silent fallback.
14
+ const PLAN_COMMAND = /^\/plan(?=$|\s)([\s\S]*)$/i;
15
+ const GOAL_COMMAND = /^\/goal(?=$|\s)([\s\S]*)$/i;
16
+
17
+ function commandResult(message) {
18
+ return { handled: true, message, messages: [message] };
19
+ }
20
+
21
+ function delegatedResultText(commandName, execution) {
22
+ const result = execution?.result;
23
+ if (!result || typeof result !== 'object'
24
+ || !['success', 'error'].includes(result.kind)
25
+ || (result.text !== undefined && typeof result.text !== 'string')) {
26
+ throw new TypeError(`Harness returned an invalid ${commandName} result`);
27
+ }
28
+ const text = result.text?.trim() ?? '';
29
+ if (text) return text;
30
+ return result.kind === 'success'
31
+ ? t('{name} 已执行。', { name: commandName })
32
+ : t('{name} 执行失败。', { name: commandName });
33
+ }
34
+
35
+ function delegatedErrorText(commandName, error) {
36
+ const code = error?.code ?? error?.failure?.code;
37
+ if (isSessionNotFound(code)) {
38
+ return t('当前聊天绑定的会话已不存在,请发送新消息开启会话。');
39
+ }
40
+ if (code === 'agent-busy') return t('当前会话正在生成回复,请稍后重试。');
41
+ if (code === 'cancelled' || error?.name === 'AbortError') return t('操作已取消。');
42
+ if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
43
+ return t('工作区或机器人状态已发生变化,请重试。');
44
+ }
45
+ if (code === 'commands-unavailable') {
46
+ return t('当前 Host 不支持命令委派,请确认 DSH 命令网关可用。');
47
+ }
48
+ return t('{name} 执行失败,请稍后重试。', { name: commandName });
49
+ }
50
+
51
+ async function runDelegatedCommand({
52
+ commandName,
53
+ commandLine,
54
+ harness,
55
+ state,
56
+ conversationKey,
57
+ options,
58
+ }) {
59
+ if (typeof state?.sessionFor !== 'function') {
60
+ return commandResult(t('当前机器人没有可用的会话状态。'));
61
+ }
62
+ const sessionId = state.sessionFor(conversationKey);
63
+ if (typeof sessionId !== 'string' || !sessionId) {
64
+ return commandResult(t('当前聊天还没有可用的会话,请先发送一条消息。'));
65
+ }
66
+ try {
67
+ let execution;
68
+ if (typeof harness?.workspaceSession === 'function') {
69
+ const session = harness.workspaceSession(sessionId, conversationKey);
70
+ if (typeof session?.executeCommand !== 'function') {
71
+ return commandResult(t('当前机器人暂不支持 {name} 命令。', { name: commandName }));
72
+ }
73
+ execution = await session.executeCommand(commandLine, options);
74
+ } else {
75
+ // Legacy Harnesses have no scoped Session handle to carry the route fence.
76
+ if (typeof harness?.executeCommand !== 'function') {
77
+ return commandResult(t('当前机器人暂不支持 {name} 命令。', { name: commandName }));
78
+ }
79
+ execution = await harness.executeCommand(sessionId, commandLine, options);
80
+ }
81
+ if (execution === undefined) {
82
+ return commandResult(t('当前 Host 未注册 {name} 命令。', { name: commandName }));
83
+ }
84
+ return commandResult(delegatedResultText(commandName, execution));
85
+ } catch (error) {
86
+ return commandResult(delegatedErrorText(commandName, error));
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Execute the Host /plan command against the IM conversation's bound Session.
92
+ * Unknown input returns null so the caller may continue ordinary message
93
+ * routing.
94
+ */
95
+ export async function runPlanCommand(text, harness, state, conversationKey, options = {}) {
96
+ if (!isPlanCommand(text)) return null;
97
+ const rest = PLAN_COMMAND.exec(text.trim())[1].trim();
98
+ return runDelegatedCommand({
99
+ commandName: '/plan',
100
+ commandLine: rest ? `/plan ${rest}` : '/plan',
101
+ harness,
102
+ state,
103
+ conversationKey,
104
+ options,
105
+ });
106
+ }
107
+
108
+ export function isPlanCommand(text) {
109
+ return typeof text === 'string' && PLAN_COMMAND.test(text.trim());
110
+ }
111
+
112
+ /**
113
+ * Execute the Host /goal command against the IM conversation's bound Session.
114
+ * Unknown input returns null so the caller may continue ordinary message
115
+ * routing.
116
+ */
117
+ export async function runGoalCommand(text, harness, state, conversationKey, options = {}) {
118
+ if (!isGoalCommand(text)) return null;
119
+ const rest = GOAL_COMMAND.exec(text.trim())[1].trim();
120
+ return runDelegatedCommand({
121
+ commandName: '/goal',
122
+ commandLine: rest ? `/goal ${rest}` : '/goal',
123
+ harness,
124
+ state,
125
+ conversationKey,
126
+ options,
127
+ });
128
+ }
129
+
130
+ export function isGoalCommand(text) {
131
+ return typeof text === 'string' && GOAL_COMMAND.test(text.trim());
132
+ }
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'node:module';
2
+
3
+ // Native require avoids empty CommonJS re-exports after DSH hot reloads (#537).
4
+ const require = createRequire(import.meta.url);
5
+ export default require('qrcode');
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Per-bot reply content filters.
3
+ *
4
+ * A Harness turn produces more than its final answer: the assistant narrates
5
+ * between tool calls ("let me check that first"), tools run, and the model may
6
+ * reason. Some conversations only want the answer. Each bot therefore keeps
7
+ * three independent switches for the parts of a turn it is willing to receive:
8
+ *
9
+ * narration -- the assistant's own prose between tool calls
10
+ * tools -- tool calls, their results and tool failures
11
+ * thinking -- the model's reasoning trace, where the channel shows one
12
+ *
13
+ * The final answer is never switchable: it is the reason the bot replies at
14
+ * all. When narration is hidden the delivered answer is also extracted after
15
+ * the last tool call, because the prose around it belongs to the process the
16
+ * user asked not to see.
17
+ *
18
+ * Kept free of Node imports so the Web client can share the same rules.
19
+ */
20
+
21
+ export const SET_REPLY_CONTENT_ENDPOINT = 'bot.reply-content.set';
22
+
23
+ /** Every key a bot may switch off; the final answer is deliberately absent. */
24
+ export const REPLY_CONTENT_KEYS = Object.freeze(['narration', 'tools', 'thinking']);
25
+
26
+ /** Defaults keep the pre-existing behaviour: a turn is delivered in full. */
27
+ export const DEFAULT_REPLY_CONTENT = Object.freeze({
28
+ narration: true,
29
+ tools: true,
30
+ thinking: true,
31
+ });
32
+
33
+ function booleanOr(value, fallback) {
34
+ return typeof value === 'boolean' ? value : fallback;
35
+ }
36
+
37
+ /**
38
+ * A complete, frozen switch set. A missing or damaged key falls back to its
39
+ * default, so one bad field can never silence a bot.
40
+ */
41
+ export function normalizeReplyContent(value) {
42
+ const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
43
+ return Object.freeze({
44
+ narration: booleanOr(source.narration, DEFAULT_REPLY_CONTENT.narration),
45
+ tools: booleanOr(source.tools, DEFAULT_REPLY_CONTENT.tools),
46
+ thinking: booleanOr(source.thinking, DEFAULT_REPLY_CONTENT.thinking),
47
+ });
48
+ }
49
+
50
+ /** Whether this switch set is the all-on default (and so need not be stored). */
51
+ export function isDefaultReplyContent(value) {
52
+ const content = normalizeReplyContent(value);
53
+ return REPLY_CONTENT_KEYS.every((key) => content[key] === DEFAULT_REPLY_CONTENT[key]);
54
+ }
55
+
56
+ /** True when at least one part of the turn is filtered out. */
57
+ export function filtersProcessContent(value) {
58
+ const content = normalizeReplyContent(value);
59
+ return REPLY_CONTENT_KEYS.some((key) => content[key] === false);
60
+ }
61
+
62
+ /**
63
+ * The answer a bot should deliver for this switch set.
64
+ *
65
+ * narration=false asks for the answer alone, so the text of every completed
66
+ * step before the last tool call is process prose rather than the answer.
67
+ */
68
+ export function replyContentFinalAnswerOnly(value) {
69
+ return normalizeReplyContent(value).narration === false;
70
+ }
71
+
72
+ /** Whether a progress update of this kind may be delivered. */
73
+ export function allowsReplyContent(value, kind) {
74
+ const content = normalizeReplyContent(value);
75
+ if (kind === 'narration' || kind === 'tools' || kind === 'thinking') return content[kind];
76
+ return true;
77
+ }
78
+
79
+ /**
80
+ * Strict shape for the settings endpoint: every switch must be present and
81
+ * boolean. Validation is separate from normalization so a malformed request is
82
+ * rejected instead of silently rewritten.
83
+ */
84
+ export function isReplyContent(value) {
85
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
86
+ && Object.keys(value).length === REPLY_CONTENT_KEYS.length
87
+ && REPLY_CONTENT_KEYS.every((key) => typeof value[key] === 'boolean');
88
+ }
89
+
90
+ /** A strict set, or a thrown error naming the field that is wrong. */
91
+ export function validateReplyContent(value) {
92
+ if (!isReplyContent(value)) {
93
+ const error = new Error('replyContent must carry boolean narration, tools and thinking switches.');
94
+ error.code = 'reply-content-invalid';
95
+ throw error;
96
+ }
97
+ return Object.freeze({
98
+ narration: value.narration,
99
+ tools: value.tools,
100
+ thinking: value.thinking,
101
+ });
102
+ }
@@ -0,0 +1,46 @@
1
+ import { t } from './i18n.mjs';
2
+ import { replaceConversationSession } from './new-command.mjs';
3
+
4
+ const RESET_COMMAND = /^\/reset(?=$|\s)([\s\S]*)$/iu;
5
+ const RESET_USAGE = '用法:/reset(不带参数且不可附带图片或文件)';
6
+
7
+ function commandResult(message) {
8
+ return { handled: true, message, messages: [message] };
9
+ }
10
+
11
+ /**
12
+ * /reset is answered locally: it creates a fresh Session through the same eager
13
+ * path /new uses and swaps it into the current ring entry in place, so the
14
+ * number stays, /ls does not grow, the title and user-titled flag survive, and
15
+ * the previous Session simply leaves this chat's ring (it is never deleted or
16
+ * archived). It never reaches the Host command registry.
17
+ */
18
+ export async function runResetCommand(text, harness, state, conversationKey, options = {}) {
19
+ if (!isResetCommand(text)) return null;
20
+ const match = RESET_COMMAND.exec(text.trim());
21
+ if (match[1].trim() || options.hasImages || options.hasFiles) {
22
+ return commandResult(t(RESET_USAGE));
23
+ }
24
+ if (options.pendingInteraction || options.busy) {
25
+ return commandResult(t('当前会话正在生成回复或等待交互,请先完成交互或发送 /stop,再执行 /reset。'));
26
+ }
27
+ if (typeof state?.sessionFor !== 'function') {
28
+ return commandResult(t('当前机器人没有可用的会话状态,未重置当前会话。'));
29
+ }
30
+ if (typeof harness?.createSession !== 'function') {
31
+ return commandResult(t('当前 Host 不支持 /reset,当前会话未修改。'));
32
+ }
33
+ const previous = state.sessionFor(conversationKey);
34
+ const result = await replaceConversationSession({ state, harness, key: conversationKey });
35
+ if (result.failed || typeof result.sessionId !== 'string' || !result.sessionId) {
36
+ return commandResult(t('重置当前会话上下文失败,当前会话未修改,请稍后重试。'));
37
+ }
38
+ if (typeof previous === 'string' && previous) {
39
+ return commandResult(t('当前会话上下文已重置(编号保持不变)。旧会话 ID:{id},可用 /session {id} 重新绑定。', { id: previous }));
40
+ }
41
+ return commandResult(t('当前聊天还没有会话,已开启全新会话。'));
42
+ }
43
+
44
+ export function isResetCommand(text) {
45
+ return typeof text === 'string' && RESET_COMMAND.test(text.trim());
46
+ }