@xmanrui/dsh-im 5.9.0 → 5.10.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 (52) hide show
  1. package/PROACTIVE_DELIVERY.en.md +33 -9
  2. package/PROACTIVE_DELIVERY.md +33 -9
  3. package/README.en.md +6 -3
  4. package/README.md +7 -4
  5. package/lib/client.js +582 -130
  6. package/lib/index.js +325 -325
  7. package/package.json +1 -1
  8. package/plugin-src/client/delivery-settings.js +2 -0
  9. package/plugin-src/client/delivery-sync-settings.js +269 -0
  10. package/plugin-src/client/global-settings.js +45 -7
  11. package/plugin-src/client/i18n-ru.js +27 -0
  12. package/plugin-src/client/i18n.js +27 -0
  13. package/plugin-src/client/index.js +17 -1
  14. package/plugin-src/client/model-setting.js +6 -3
  15. package/plugin-src/client/styles.js +16 -0
  16. package/plugin-src/host/channels/feishu/production.mjs +11 -27
  17. package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
  18. package/plugin-src/host/delivery-adapter.mjs +35 -20
  19. package/plugin-src/host/delivery-service.mjs +100 -1
  20. package/plugin-src/host/delivery-suggestions.mjs +28 -0
  21. package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
  22. package/plugin-src/host/host-language-rpc.mjs +16 -2
  23. package/plugin-src/host/host-language.mjs +29 -0
  24. package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
  25. package/plugin-src/host/index.mjs +23 -1
  26. package/plugin-src/host/session-sync-coordinator.mjs +288 -121
  27. package/plugin-src/host/session-sync-targets.mjs +71 -0
  28. package/plugin-src/host/sidebar-settings.mjs +1 -2
  29. package/plugin-src/host/update-rpc.mjs +1 -1
  30. package/plugin-src/management-rpc.mjs +25 -3
  31. package/scripts/verify-lan-management.mjs +58 -5
  32. package/scripts/verify-package.mjs +14 -5
  33. package/src/channels/email/email-runtime.mjs +27 -8
  34. package/src/channels/feishu/bridge.mjs +250 -3
  35. package/src/channels/qq/qq-bridge.mjs +9 -0
  36. package/src/channels/qq/state-store.mjs +42 -0
  37. package/src/channels/shared/action-card.mjs +83 -7
  38. package/src/channels/shared/bot-workspace-store.mjs +100 -8
  39. package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
  40. package/src/channels/shared/delivery-sync-settings.mjs +122 -0
  41. package/src/channels/shared/harness-client.mjs +148 -90
  42. package/src/channels/shared/i18n-en/diagnostics.mjs +7 -1
  43. package/src/channels/shared/i18n-en/feishu.mjs +3 -0
  44. package/src/channels/shared/i18n-en/shared-b.mjs +6 -0
  45. package/src/channels/shared/i18n-ru/diagnostics.mjs +11 -0
  46. package/src/channels/shared/i18n-ru/feishu.mjs +2 -0
  47. package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
  48. package/src/channels/shared/interface-language-store.mjs +49 -10
  49. package/src/channels/shared/interface-language.mjs +19 -1
  50. package/src/channels/shared/model-setting.mjs +6 -3
  51. package/src/channels/shared/workspace-session.mjs +13 -1
  52. package/src/channels/telegram/telegram-api.mjs +19 -1
@@ -169,6 +169,23 @@ export function consumeDshImInputOrigin(scope, rpcId) {
169
169
  return origins.delete(rpcId);
170
170
  }
171
171
 
172
+ /**
173
+ * Whether a dsh-im prompt id is registered, without claiming it.
174
+ *
175
+ * An observer such as the Session sync coordinator must be able to ask "did a
176
+ * messenger start this turn?" without taking the id away from the channel that
177
+ * still owns it. The entry lives until its TTL or the size cap evicts it, so a
178
+ * repeated question keeps answering the same way, while the one-shot
179
+ * `consumeDshImInputOrigin` stays the only way to claim it.
180
+ */
181
+ export function isDshImInputOrigin(scope, rpcId) {
182
+ if (!scope || !['object', 'function', 'string'].includes(typeof scope)
183
+ || typeof rpcId !== 'string' || !rpcId) return false;
184
+ const origins = interactionRegistry(scope).imInputOrigins;
185
+ pruneImInputOrigins(origins);
186
+ return origins.has(rpcId);
187
+ }
188
+
172
189
  // A Host RPC may not accept cancellation itself. Bound the caller's wait
173
190
  // without retrying an operation that the Host may already have accepted.
174
191
  function callWithSignal(call, signal) {
@@ -1497,6 +1514,10 @@ export class HarnessClient {
1497
1514
  return false;
1498
1515
  }
1499
1516
 
1517
+ async isSessionArchived(sessionId, options = {}) {
1518
+ return this.#isSessionArchived(sessionId, options);
1519
+ }
1520
+
1500
1521
  async sessionExists(sessionId, options = {}) {
1501
1522
  // Archived Sessions still exist. Returning false here would silently bind
1502
1523
  // the conversation to a new Session; reading their active log can also fail.
@@ -1878,7 +1899,45 @@ export class HarnessClient {
1878
1899
  }
1879
1900
  }
1880
1901
 
1881
- async #ask(sessionId, prompt, options, diagnostic) {
1902
+ /** Follow a prompt DS Bot carried to another Session, without submitting it again. */
1903
+ async waitForTransferredReply(sessionId, { promptRpcId, ...options } = {}) {
1904
+ if (typeof promptRpcId !== 'string' || !promptRpcId) {
1905
+ throw new TypeError('Transferred prompt identity is required');
1906
+ }
1907
+ const diagnostic = { stage: 'reply.wait', submissionState: 'accepted', sessionId, promptRpcId };
1908
+ try {
1909
+ return await this.#ask(sessionId, null, options, diagnostic, promptRpcId);
1910
+ } catch (error) {
1911
+ if (options.signal?.aborted) throw options.signal.reason ?? error;
1912
+ // Preflight failures must retain the accepted input's identity too. A
1913
+ // fresh part may itself have rolled over before its watcher was opened.
1914
+ error.promptAccepted = true;
1915
+ error.details = { sessionId, promptRpcId, baselineSeq: -1, ...error.details };
1916
+ throw messageDiagnosticError(error, diagnostic);
1917
+ }
1918
+ }
1919
+
1920
+ async #replyHistory(sessionId, afterSeq, transferred, signal) {
1921
+ const events = [];
1922
+ let beforeSeq;
1923
+ for (let page = 0; page < 20; page += 1) {
1924
+ signal?.throwIfAborted();
1925
+ const history = await this.#sessionRpc('session.history', {
1926
+ sessionId, maxMessages: 50,
1927
+ ...(beforeSeq === undefined ? {} : { beforeSeq }),
1928
+ }, 30_000, { signal });
1929
+ signal?.throwIfAborted();
1930
+ events.push(...(history.events ?? []));
1931
+ const oldest = Math.min(...(history.events ?? []).map((entry) => (entry.event ?? entry).seq));
1932
+ if (!transferred || !history.hasMore || oldest <= afterSeq + 1) return { events };
1933
+ if (!Number.isSafeInteger(oldest) || oldest === beforeSeq) break;
1934
+ beforeSeq = oldest;
1935
+ }
1936
+ // Do not attribute or complete a turn from an incomplete replay window.
1937
+ return { events: [] };
1938
+ }
1939
+
1940
+ async #ask(sessionId, prompt, options, diagnostic, transferredPromptRpcId = null) {
1882
1941
  const timeoutMs = options.timeoutMs ?? 600_000;
1883
1942
  const signal = options.signal;
1884
1943
  const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
@@ -1896,18 +1955,18 @@ export class HarnessClient {
1896
1955
  ? options.onInteractionResolved
1897
1956
  : undefined;
1898
1957
  const control = normalizeControl(options.control);
1899
- const inboundFiles = Array.isArray(options.files) ? options.files.filter(Boolean) : [];
1900
- const inboundImages = Array.isArray(options.images) ? options.images.filter(Boolean) : [];
1958
+ const inboundFiles = !transferredPromptRpcId && Array.isArray(options.files) ? options.files.filter(Boolean) : [];
1959
+ const inboundImages = !transferredPromptRpcId && Array.isArray(options.images) ? options.images.filter(Boolean) : [];
1901
1960
  await this.ensureRunning({ signal });
1902
1961
  if (await this.#isSessionArchived(sessionId, { signal })) throw sessionArchivedError(sessionId);
1903
- const before = await this.#sessionRpc(
1962
+ const before = transferredPromptRpcId ? { events: [] } : await this.#sessionRpc(
1904
1963
  'session.history',
1905
1964
  { sessionId, maxMessages: 1 },
1906
1965
  30_000,
1907
1966
  { signal },
1908
1967
  );
1909
1968
  const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
1910
- const promptRpcId = `${this.#rpcIdPrefix}-${randomUUID()}`;
1969
+ const promptRpcId = transferredPromptRpcId ?? `${this.#rpcIdPrefix}-${randomUUID()}`;
1911
1970
  diagnostic.promptRpcId = promptRpcId;
1912
1971
  const releasePromptInputOrigin = registerImInputOrigin(this.#interactionRegistry, promptRpcId);
1913
1972
  const tracker = new HarnessReplyTracker({
@@ -1983,9 +2042,10 @@ export class HarnessClient {
1983
2042
  let artifactsDelivered = false;
1984
2043
  let deliveredArtifactCount = 0;
1985
2044
  let artifactHandoffError = null;
1986
- const stagedBatches = [];
1987
- let promptAccepted = false;
2045
+ const stagedBatches = options.handoffResources?.stagedBatches ?? [];
2046
+ let promptAccepted = Boolean(transferredPromptRpcId);
1988
2047
  let turnFinished = false;
2048
+ let handedOff = false;
1989
2049
 
1990
2050
  const deliverArtifacts = async () => {
1991
2051
  if (!onArtifact || artifactsDelivered || tracker.turn === null) {
@@ -2076,87 +2136,86 @@ export class HarnessClient {
2076
2136
  }),
2077
2137
  ]);
2078
2138
  }
2079
- diagnostic.stage = 'prompt.prepare';
2080
- const content = typeof prompt === 'string'
2081
- ? [{ type: 'text', text: prompt }]
2082
- : prompt;
2083
- if (!Array.isArray(content) || content.length === 0) {
2084
- throw new TypeError('Harness prompt content is required');
2085
- }
2086
- // Publish the guidance the channel's own captured settings produced, so
2087
- // the Host materializes it once per Session as prompt context instead of
2088
- // per user message. It is passed in and never parsed back out of
2089
- // `content`: the prompt also carries whatever the user typed, and a
2090
- // message that merely looks like a guidance block is not configuration.
2139
+ // Restore the channel's trusted guidance in a fresh part too; never
2140
+ // derive it from the forwarded message's content.
2091
2141
  imSourceGuidance.publish(sessionId, options.sourceGuidance);
2092
- const timeZoneFields = clientTimeZoneFields();
2093
- const sendPrompt = (promptContent) => {
2094
- diagnostic.stage = 'prompt.submit';
2095
- diagnostic.submissionState = 'unknown';
2096
- return this.#sessionRpc('session.prompt', {
2097
- sessionId,
2098
- mode: 'queue',
2099
- content: promptContent,
2100
- ...timeZoneFields,
2101
- }, 30_000, { rpcId: promptRpcId, signal });
2102
- };
2103
- // 30 秒提交窗口到期只说明 Host 忙到没来得及应答,prompt 可能早已入队。
2104
- // 先按 promptRpcId 回查持久账本,确认入库就继续等回复;确认不到才把
2105
- // 原始超时错误向上抛,由文案层标注「提交请求超时、是否送达未知」。
2106
- const submitPrompt = async (promptContent) => {
2107
- try {
2108
- await sendPrompt(promptContent);
2109
- } catch (error) {
2110
- if (!isPromptSubmitTimeout(error) || signal?.aborted) throw error;
2111
- let confirmed = false;
2112
- try {
2113
- confirmed = await this.#confirmPromptSubmit(sessionId, promptRpcId, { signal });
2114
- } catch (confirmError) {
2115
- // 确认途中被取消时恢复调用方的取消语义(与图片暂存路径一致)。
2116
- if (signal?.aborted) throw signal.reason ?? confirmError;
2117
- throw error;
2118
- }
2119
- if (!confirmed) throw error;
2120
- diagnostic.submissionState = 'accepted';
2142
+ if (!transferredPromptRpcId) {
2143
+ diagnostic.stage = 'prompt.prepare';
2144
+ const content = typeof prompt === 'string'
2145
+ ? [{ type: 'text', text: prompt }]
2146
+ : prompt;
2147
+ if (!Array.isArray(content) || content.length === 0) {
2148
+ throw new TypeError('Harness prompt content is required');
2121
2149
  }
2122
- };
2123
- try {
2124
- await submitPrompt(content);
2125
- } catch (error) {
2126
- // The Host refuses image blocks for a non-vision model before any
2127
- // durable user message exists. Re-deliver the same bytes the way
2128
- // ordinary uploads (zip, documents) already travel — staged into the
2129
- // Session workspace and named in a text manifest — then retry once
2130
- // with a text-only prompt. The retry reuses promptRpcId so reply
2131
- // tracking, control and interaction ownership stay bound to this ask.
2132
- const originalsStaged = inboundImages.length > 0 && isImageAdmissionRejection(error)
2133
- && content.some((part) => part.type === 'image');
2134
- const imageSources = !originalsStaged && isModelImageRejection(error)
2135
- ? imageFileSourcesFromContent(content) : [];
2136
- if (!originalsStaged && imageSources.length === 0) throw error;
2137
- if (!originalsStaged) {
2138
- let stagedImages;
2150
+ const timeZoneFields = clientTimeZoneFields();
2151
+ const sendPrompt = (promptContent) => {
2152
+ diagnostic.stage = 'prompt.submit';
2153
+ diagnostic.submissionState = 'unknown';
2154
+ return this.#sessionRpc('session.prompt', {
2155
+ sessionId,
2156
+ mode: 'queue',
2157
+ content: promptContent,
2158
+ ...timeZoneFields,
2159
+ }, 30_000, { rpcId: promptRpcId, signal });
2160
+ };
2161
+ // 30 秒提交窗口到期只说明 Host 忙到没来得及应答,prompt 可能早已入队。
2162
+ // 先按 promptRpcId 回查持久账本,确认入库就继续等回复;确认不到才把
2163
+ // 原始超时错误向上抛,由文案层标注「提交请求超时、是否送达未知」。
2164
+ const submitPrompt = async (promptContent) => {
2139
2165
  try {
2140
- stagedImages = await this.#stageWorkspaceFiles(sessionId, imageSources, signal);
2141
- } catch (stagingError) {
2142
- if (signal?.aborted) throw signal.reason ?? stagingError;
2143
- console.warn(
2144
- '[dsh-im] unable to restage rejected images as workspace files:',
2145
- this.#logPrefix,
2146
- stagingError?.message ?? String(stagingError),
2147
- );
2148
- throw error;
2166
+ await sendPrompt(promptContent);
2167
+ } catch (error) {
2168
+ if (!isPromptSubmitTimeout(error) || signal?.aborted) throw error;
2169
+ let confirmed = false;
2170
+ try {
2171
+ confirmed = await this.#confirmPromptSubmit(sessionId, promptRpcId, { signal });
2172
+ } catch (confirmError) {
2173
+ // 确认途中被取消时恢复调用方的取消语义(与图片暂存路径一致)。
2174
+ if (signal?.aborted) throw signal.reason ?? confirmError;
2175
+ throw error;
2176
+ }
2177
+ if (!confirmed) throw error;
2178
+ diagnostic.submissionState = 'accepted';
2179
+ }
2180
+ };
2181
+ try {
2182
+ await submitPrompt(content);
2183
+ } catch (error) {
2184
+ // The Host refuses image blocks for a non-vision model before any
2185
+ // durable user message exists. Re-deliver the same bytes the way
2186
+ // ordinary uploads (zip, documents) already travel — staged into the
2187
+ // Session workspace and named in a text manifest — then retry once
2188
+ // with a text-only prompt. The retry reuses promptRpcId so reply
2189
+ // tracking, control and interaction ownership stay bound to this ask.
2190
+ const originalsStaged = inboundImages.length > 0 && isImageAdmissionRejection(error)
2191
+ && content.some((part) => part.type === 'image');
2192
+ const imageSources = !originalsStaged && isModelImageRejection(error)
2193
+ ? imageFileSourcesFromContent(content) : [];
2194
+ if (!originalsStaged && imageSources.length === 0) throw error;
2195
+ if (!originalsStaged) {
2196
+ let stagedImages;
2197
+ try {
2198
+ stagedImages = await this.#stageWorkspaceFiles(sessionId, imageSources, signal);
2199
+ } catch (stagingError) {
2200
+ if (signal?.aborted) throw signal.reason ?? stagingError;
2201
+ console.warn(
2202
+ '[dsh-im] unable to restage rejected images as workspace files:',
2203
+ this.#logPrefix,
2204
+ stagingError?.message ?? String(stagingError),
2205
+ );
2206
+ throw error;
2207
+ }
2208
+ stagedBatches.push(stagedImages);
2149
2209
  }
2150
- stagedBatches.push(stagedImages);
2210
+ const baseContent = typeof basePrompt === 'string'
2211
+ ? [{ type: 'text', text: basePrompt }]
2212
+ : basePrompt;
2213
+ const fallbackPrompt = appendInboundFilesToPrompt([
2214
+ ...contentWithoutImages(baseContent),
2215
+ { type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
2216
+ ], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
2217
+ await submitPrompt(fallbackPrompt);
2151
2218
  }
2152
- const baseContent = typeof basePrompt === 'string'
2153
- ? [{ type: 'text', text: basePrompt }]
2154
- : basePrompt;
2155
- const fallbackPrompt = appendInboundFilesToPrompt([
2156
- ...contentWithoutImages(baseContent),
2157
- { type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
2158
- ], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
2159
- await submitPrompt(fallbackPrompt);
2160
2219
  }
2161
2220
  promptAccepted = true;
2162
2221
  diagnostic.submissionState = 'accepted';
@@ -2170,12 +2229,9 @@ export class HarnessClient {
2170
2229
  // active until turn/end and can therefore outlive a stalled turn.
2171
2230
  while (true) {
2172
2231
  await sleep(300, signal);
2173
- const history = await this.#sessionRpc(
2174
- 'session.history',
2175
- { sessionId, maxMessages: 50 },
2176
- 30_000,
2177
- { signal },
2178
- );
2232
+ options.assertCurrent?.();
2233
+ const history = await this.#replyHistory(sessionId, tracker.lastSeq, Boolean(transferredPromptRpcId), signal);
2234
+ options.assertCurrent?.();
2179
2235
  const wasActive = ownership?.active === true;
2180
2236
  if (ownership) {
2181
2237
  this.#consumeInteractionOwnerships(sessionId, history.events ?? []);
@@ -2252,6 +2308,8 @@ export class HarnessClient {
2252
2308
  throw timeoutError;
2253
2309
  }
2254
2310
  } catch (error) {
2311
+ handedOff = Boolean(options.handoffResources)
2312
+ && ['turn-blocked', 'session-archived'].includes(error.code);
2255
2313
  if (error.code === 'session-archived') {
2256
2314
  error.promptAccepted = promptAccepted;
2257
2315
  error.details = { ...error.details, promptRpcId, baselineSeq, turn: tracker.turn, lastSeq: tracker.lastSeq };
@@ -2272,7 +2330,7 @@ export class HarnessClient {
2272
2330
  }
2273
2331
  } finally {
2274
2332
  releasePromptInputOrigin();
2275
- if (!promptAccepted || turnFinished) {
2333
+ if (!promptAccepted || (turnFinished && !handedOff)) {
2276
2334
  for (const staged of stagedBatches) {
2277
2335
  try {
2278
2336
  await staged?.cleanup?.();
@@ -1,4 +1,5 @@
1
1
  export default Object.freeze({
2
+ '无法读取所选模型的列表,模型设置未保存,请重试。': 'Could not load the selected model’s catalog. The model setting was not saved. Try again.',
2
3
  '异常类型': 'Exception types',
3
4
  '二维码编码器': 'QR encoder',
4
5
  '二维码图片格式': 'QR image format',
@@ -85,5 +86,10 @@ export default Object.freeze({
85
86
  "超时阈值(毫秒)": "Timeout (ms)",
86
87
  "Node 版本": "Node version",
87
88
  "运行平台": "Platform",
88
- "无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again."
89
+ "无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again.",
90
+ "DSH 登录状态无效或已过期,请通过有效启动链接重新登录。": "Your DSH session is invalid or expired. Sign in again using a valid launch link.",
91
+ "DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。": "DSH denied this management request (HTTP 403). Check access permissions, trusted hosts and proxy settings. If local-only access is enabled, use an allowed local connection.",
92
+ "DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。": "The DSH management API was not found (HTTP 404). Check the Host and plugin versions and proxy path, then restart and retry.",
93
+ "DSH 管理服务暂时异常,请检查服务状态或稍后重试。": "The DSH management service encountered an error. Check its status or try again later.",
94
+ "DSH 管理请求失败,请检查服务状态和网络连接后重试。": "The DSH management request failed. Check the service status and network connection, then retry."
89
95
  });
@@ -407,6 +407,9 @@ export default {
407
407
  '任务失败': 'Failed',
408
408
  // feishu/bridge.mjs — step push context injection
409
409
  '📎 已注入会话上下文': '📎 Context injected',
410
+ // feishu/bridge.mjs — goal rounds opened outside the IM (issue #454)
411
+ '🔄 目标自动续跑': '🔄 Goal auto-continued',
412
+ '🔄 目标自动续跑(第 {round} 轮)': '🔄 Goal auto-continued (round {round})',
410
413
  // feishu/feishu-cards.mjs — question card answered state + custom entry (issue #162)
411
414
  '✏️ 其他答案…': '✏️ Other answer…',
412
415
  '✅ 已回答{progress}': '✅ Answered{progress}',
@@ -294,4 +294,10 @@ export default {
294
294
  'A queued message was interrupted when the service restarted. It was not replayed automatically to avoid running it twice; if it was not processed, please send it again.',
295
295
  '已提交补充指令,Agent 会在下一步读取。':
296
296
  'Additional instruction submitted; the Agent will read it at the next step.',
297
+ // delivery-sync-rpc.mjs
298
+ '请求已取消。': 'The request was cancelled.',
299
+ '无效的会话同步设置:开关必须是布尔值,图标是不超过 32 个字符的文本。':
300
+ 'Invalid Session sync settings: each switch must be a boolean and an icon is text of at most 32 characters.',
301
+ '无法读取或保存会话同步设置,请稍后重试。':
302
+ 'Could not read or save Session sync settings. Try again later.',
297
303
  };
@@ -1,4 +1,5 @@
1
1
  export default Object.freeze({
2
+ '无法读取所选模型的列表,模型设置未保存,请重试。': 'Не удалось загрузить список выбранного провайдера моделей. Настройка модели не сохранена. Повторите попытку.',
2
3
  '异常类型': 'Тип исключения',
3
4
  '二维码编码器': 'Кодировщик QR-кода',
4
5
  '二维码图片格式': 'Формат изображения QR-кода',
@@ -103,4 +104,14 @@ export default Object.freeze({
103
104
  '运行平台': 'Платформа',
104
105
  '无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。':
105
106
  'Нет доступа к административному API DSH. Проверьте соединение с DSH или войдите заново.',
107
+ 'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。':
108
+ 'Сеанс DSH недействителен или истёк. Войдите снова по действующей ссылке запуска.',
109
+ 'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。':
110
+ 'DSH отклонил запрос управления (HTTP 403). Проверьте права доступа, доверенные адреса и настройки прокси. Если разрешён только локальный доступ, используйте разрешённое локальное подключение.',
111
+ 'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。':
112
+ 'API управления DSH не найден (HTTP 404). Проверьте версии Host и плагина, а также путь прокси, затем перезапустите и повторите попытку.',
113
+ 'DSH 管理服务暂时异常,请检查服务状态或稍后重试。':
114
+ 'В службе управления DSH произошла ошибка. Проверьте её состояние или повторите попытку позже.',
115
+ 'DSH 管理请求失败,请检查服务状态和网络连接后重试。':
116
+ 'Запрос управления DSH не выполнен. Проверьте состояние службы и подключение к сети, затем повторите попытку.',
106
117
  });
@@ -368,6 +368,8 @@ export default {
368
368
  'Не удалось безопасно остановить фоновую задачу. Найдите соответствующую задачу в Harness и остановите её.',
369
369
  '任务失败': 'Не удалось',
370
370
  '📎 已注入会话上下文': '📎 Контекст добавлен',
371
+ '🔄 目标自动续跑': '🔄 Цель продолжена автоматически',
372
+ '🔄 目标自动续跑(第 {round} 轮)': '🔄 Цель продолжена автоматически (раунд {round})',
371
373
  '✏️ 其他答案…': '✏️ Другой ответ…',
372
374
  '✅ 已回答{progress}': '✅ Ответ дан{progress}',
373
375
  '✅ 已选择:{label}': '✅ Выбрано: {label}',
@@ -259,4 +259,9 @@ export default {
259
259
  'Сообщение в очереди было прервано перезапуском сервиса. Чтобы не выполнить его дважды, автоматически не повторяли; если оно не обработано, отправьте его заново.',
260
260
  '已提交补充指令,Agent 会在下一步读取。':
261
261
  'Дополнительное указание отправлено, Agent прочитает его на следующем шаге.',
262
+ '请求已取消。': 'Запрос отменён.',
263
+ '无效的会话同步设置:开关必须是布尔值,图标是不超过 32 个字符的文本。':
264
+ 'Неверные настройки синхронизации сеанса: каждый переключатель должен быть логическим, а значок — текст не длиннее 32 символов.',
265
+ '无法读取或保存会话同步设置,请稍后重试。':
266
+ 'Не удалось прочитать или сохранить настройки синхронизации сеанса. Повторите попытку позже.',
262
267
  };
@@ -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;
@@ -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
  }
@@ -232,12 +232,24 @@ export async function askInWorkspaceSession({
232
232
  throw error;
233
233
  }
234
234
  return {
235
- sessionId: binding.sessionId,
235
+ sessionId: binding.session.replySessionId ?? binding.sessionId,
236
236
  answer,
237
237
  ...(artifacts.length > 0 ? { artifacts } : {}),
238
238
  };
239
239
  } catch (error) {
240
240
  const failure = messageDiagnosticError(error, diagnostic);
241
+ if (dsBotSession && error?.code === 'session-archived'
242
+ && extractConnectionEvidence(failure).details.submissionState === 'not-submitted') {
243
+ let freshSessionId = null;
244
+ for (let attempt = 0; attempt < 6; attempt += 1) {
245
+ freshSessionId = await harness.resolveDsBotSession?.(key).catch(() => null);
246
+ if (freshSessionId && freshSessionId !== diagnostic.sessionId) break;
247
+ await new Promise((resolve) => setTimeout(resolve, 200));
248
+ }
249
+ if (freshSessionId && freshSessionId !== diagnostic.sessionId) {
250
+ continue;
251
+ }
252
+ }
241
253
  // Retry once, only with positive evidence that no prompt was submitted.
242
254
  // The binding lock rechecks identity so a concurrent /new or workspace
243
255
  // switch cannot be overwritten by recovery of the previous Session.
@@ -141,8 +141,26 @@ function inputReplyMarkup(value) {
141
141
  }
142
142
  return row.map((button) => {
143
143
  const text = cleanString(button?.text);
144
+ if (!text) {
145
+ throw new TypeError('Telegram inline keyboard buttons require text');
146
+ }
147
+ // Bot API 10.3 added `DisabledButton`: a labelled button that does
148
+ // nothing. The spec allows exactly one action field per button, so a
149
+ // disabled button must NOT also carry callback_data — that is why the
150
+ // two are mutually exclusive here instead of simply merged.
151
+ if (button?.disabled !== undefined) {
152
+ if (button.disabled !== null && typeof button.disabled !== 'object') {
153
+ throw new TypeError('Telegram disabled buttons take an empty object');
154
+ }
155
+ if (button.callback_data !== undefined) {
156
+ throw new TypeError(
157
+ 'A disabled Telegram button must not carry callback_data',
158
+ );
159
+ }
160
+ return { text, disabled: {} };
161
+ }
144
162
  const data = cleanString(button?.callback_data);
145
- if (!text || !data) {
163
+ if (!data) {
146
164
  throw new TypeError('Telegram inline keyboard buttons require text and callback_data');
147
165
  }
148
166
  if (Buffer.byteLength(data, 'utf8') > CALLBACK_DATA_MAX_BYTES) {