@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
@@ -5,6 +5,8 @@ import { isControlCommand } from './control-command.mjs';
5
5
  import { isHistoryCommand } from './history-command.mjs';
6
6
  import { isModelCommand } from './model-command.mjs';
7
7
  import { isPresetCommand } from './preset-command.mjs';
8
+ import { isPlanCommand, isGoalCommand } from './plan-goal-command.mjs';
9
+ import { isResetCommand } from './reset-command.mjs';
8
10
  import { isWorkspaceCommand } from './workspace-command.mjs';
9
11
 
10
12
  const SIMPLE_TEXT_COMMANDS = new Set(['/help', '/status', '/new']);
@@ -21,7 +23,7 @@ export function isSharedLocalCommand(text, {
21
23
  const command = text.trim();
22
24
  if (!command) return false;
23
25
  if (isBatchInputCommand(command) || isHistoryCommand(command)) return true;
24
- if (isClearCommand(command)) return true;
26
+ if (isClearCommand(command) || isResetCommand(command)) return true;
25
27
  if (!hasFiles && (
26
28
  isControlCommand(command)
27
29
  || isModelCommand(command)
@@ -30,5 +32,7 @@ export function isSharedLocalCommand(text, {
30
32
  if (hasImages || hasFiles) return false;
31
33
  return SIMPLE_TEXT_COMMANDS.has(command.toLowerCase())
32
34
  || isWorkspaceCommand(command)
33
- || isCompactCommand(command);
35
+ || isCompactCommand(command)
36
+ || isPlanCommand(command)
37
+ || isGoalCommand(command);
34
38
  }
@@ -1,6 +1,11 @@
1
1
  import { deferredStateAccess, normalizeDeferredState } from './deferred-state.mjs';
2
2
  import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
+ import {
5
+ createSessionRingSupport,
6
+ normalizePendingTitles,
7
+ normalizeSessionRings,
8
+ } from './session-ring-support.mjs';
4
9
 
5
10
  /**
6
11
  * Additional persisted keys a subclass may own. Kept intentionally small and
@@ -119,6 +124,10 @@ function normalizeState(value) {
119
124
  : [],
120
125
  cursor: Number.isSafeInteger(value.cursor) && value.cursor >= 0 ? value.cursor : null,
121
126
  };
127
+ const rings = normalizeSessionRings(value.rings);
128
+ if (Object.keys(rings).length) normalized.rings = rings;
129
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
130
+ if (Object.keys(pendingTitles).length) normalized.pendingTitles = pendingTitles;
122
131
  // Channel-specific extensions survive a reload; each is normalized by the
123
132
  // subclass that owns it (see extensionKeys()).
124
133
  for (const key of EXTENSION_KEYS) {
@@ -135,6 +144,13 @@ export class ConversationStateStore {
135
144
 
136
145
  constructor(path) {
137
146
  this.#path = path;
147
+ // The ring is not a store of its own: it is a view over this state object,
148
+ // shared with the channels that assemble their own store, so both sides
149
+ // cannot drift apart.
150
+ Object.assign(this, createSessionRingSupport({
151
+ state: () => this.#state,
152
+ persist: () => this.#persist(),
153
+ }));
138
154
  }
139
155
 
140
156
  async load() {
@@ -106,7 +106,12 @@ export function createDeferredDeliveryCoordinator({
106
106
  }
107
107
  const outcome = targetTurn === null
108
108
  ? { found: false, endSeq: -1, turn: null }
109
- : extractCompletedTurnAnswer(ordered, { turn: targetTurn, finalAnswerOnly });
109
+ : extractCompletedTurnAnswer(ordered, {
110
+ turn: targetTurn,
111
+ // A turn registered by a bot that hides process prose keeps that
112
+ // choice when it is delivered from the background.
113
+ finalAnswerOnly: entry.finalAnswerOnly === true || finalAnswerOnly,
114
+ });
110
115
  const hasStart = ordered.some((event) => event.type === 'turn/start' && event.data?.turn === targetTurn);
111
116
  if (!history.hasMore || hasStart) return { ...outcome, turn: targetTurn };
112
117
  const oldest = batch[0]?.seq;
@@ -106,6 +106,7 @@ export function createDeferredDeliveryRegistry(store, {
106
106
  deferredId,
107
107
  async register({
108
108
  key, chatId = null, target = null, replyToMessageId = null, sessionId, turn = null, afterSeq = -1, promptRpcId = null,
109
+ finalAnswerOnly = false,
109
110
  }) {
110
111
  if (typeof key !== 'string' || !key) throw new TypeError('key is required');
111
112
  if ((!chatId || typeof chatId !== 'string') && (!target || typeof target !== 'object')) {
@@ -126,6 +127,9 @@ export function createDeferredDeliveryRegistry(store, {
126
127
  attempts: 0,
127
128
  status: 'pending',
128
129
  createdAt: now(),
130
+ // Remembered per turn: the background path must keep delivering what
131
+ // the foreground turn would have delivered.
132
+ ...(finalAnswerOnly === true ? { finalAnswerOnly: true } : {}),
129
133
  };
130
134
  const sameKey = (await store.listDeferred())
131
135
  .filter((candidate) => candidate.key === key && candidate.status === 'pending');
@@ -0,0 +1,86 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+
6
+ import {
7
+ applyDeliverySyncPatch,
8
+ DEFAULT_DELIVERY_SYNC_SETTINGS,
9
+ DELIVERY_SYNC_SETTINGS_VERSION,
10
+ normalizeDeliverySyncSettings,
11
+ } from './delivery-sync-settings.mjs';
12
+
13
+ const stores = new Map();
14
+
15
+ /**
16
+ * One settings document for the whole plugin: which non-IM turns reach a chat
17
+ * and which prefixes mark them. Mirrors ImageInputSettingsStore: atomic
18
+ * rename, serialized writes, and a damaged document falls back to the defaults
19
+ * instead of failing the Host.
20
+ */
21
+ export class DeliverySyncSettingsStore {
22
+ #path;
23
+ #settings = DEFAULT_DELIVERY_SYNC_SETTINGS;
24
+ #ready;
25
+ #writes = Promise.resolve();
26
+
27
+ constructor(path) {
28
+ if (typeof path !== 'string' || !path) {
29
+ throw new TypeError('delivery sync settings store path is required');
30
+ }
31
+ this.#path = path;
32
+ }
33
+
34
+ async get() {
35
+ this.#ready ??= this.#load().catch((error) => { this.#ready = null; throw error; });
36
+ await this.#ready;
37
+ return { ...this.#settings };
38
+ }
39
+
40
+ async #load() {
41
+ let raw;
42
+ try { raw = await readFile(this.#path, 'utf8'); }
43
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
44
+ let document;
45
+ try { document = JSON.parse(raw); } catch { return; }
46
+ if (!document || typeof document !== 'object' || Array.isArray(document)) return;
47
+ if (document.version !== DELIVERY_SYNC_SETTINGS_VERSION) return;
48
+ // A document with a broken body keeps the defaults; a readable one wins.
49
+ this.#settings = normalizeDeliverySyncSettings(document.deliverySync) ?? DEFAULT_DELIVERY_SYNC_SETTINGS;
50
+ }
51
+
52
+ /** Apply a partial update: only the fields present in `patch` are written. */
53
+ async set(patch) {
54
+ const operation = this.#writes.catch(() => {}).then(async () => {
55
+ const current = await this.get();
56
+ const settings = applyDeliverySyncPatch(current, patch);
57
+ await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
58
+ const temporary = `${this.#path}.${randomUUID()}.tmp`;
59
+ try {
60
+ await writeFile(
61
+ temporary,
62
+ `${JSON.stringify({ version: DELIVERY_SYNC_SETTINGS_VERSION, deliverySync: settings }, null, 2)}\n`,
63
+ { mode: 0o600, flag: 'wx' },
64
+ );
65
+ await rename(temporary, this.#path);
66
+ this.#settings = settings;
67
+ } finally { await rm(temporary, { force: true }); }
68
+ return { ...settings };
69
+ });
70
+ this.#writes = operation;
71
+ return operation;
72
+ }
73
+ }
74
+
75
+ /** Path of the document, for diagnostics and tests. */
76
+ export function deliverySyncSettingsPath(config = {}) {
77
+ const root = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
78
+ return join(root, 'integrations', 'dsh-im', 'delivery-sync-settings.json');
79
+ }
80
+
81
+ /** One settings owner per DSH home, shared by the UI, the RPC and the coordinator. */
82
+ export function getDeliverySyncSettingsStore(config = {}) {
83
+ const path = deliverySyncSettingsPath(config);
84
+ if (!stores.has(path)) stores.set(path, new DeliverySyncSettingsStore(path));
85
+ return stores.get(path);
86
+ }
@@ -0,0 +1,122 @@
1
+ // Global (not per-bot) settings that decide whether dsh-im delivers turns the
2
+ // IM user did not start themselves: a turn initiated in the DSH Web GUI and a
3
+ // turn initiated by a service notice (a schedule reminder, a subagent settling,
4
+ // an answered question). The same document also carries the two text prefixes
5
+ // that mark a mirrored user message and a delivered model answer.
6
+
7
+ export const DELIVERY_SYNC_SETTINGS_VERSION = 1;
8
+
9
+ /** Longest accepted icon prefix, in characters. */
10
+ export const DELIVERY_SYNC_ICON_MAX_LENGTH = 32;
11
+
12
+ export const DEFAULT_DELIVERY_SYNC_SETTINGS = Object.freeze({
13
+ // Mirror the user's own Web input into the chat. Off by default: a chat that
14
+ // receives every desktop keystroke is noisy until the reader asks for it.
15
+ mirrorUserInput: false,
16
+ // Deliver the model answer of a turn that did not start in this chat. Off by
17
+ // default like the input mirror: mirroring is something the reader asks for,
18
+ // never something a fresh or unreadable document starts on its own.
19
+ deliverModelAnswers: false,
20
+ inputIcon: '',
21
+ modelIcon: '',
22
+ });
23
+
24
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f-\u009f]/u;
25
+
26
+ function isRecord(value) {
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ }
29
+
30
+ /**
31
+ * Normalize one message prefix. The empty string is a valid prefix (no prefix
32
+ * at all), so a malformed icon degrades to "no icon" instead of failing the
33
+ * whole save — a reader who pastes 40 emoji should lose the icon, not the
34
+ * checkbox they just set.
35
+ */
36
+ export function normalizeDeliverySyncIcon(value) {
37
+ if (typeof value !== 'string') return '';
38
+ const trimmed = value.trim();
39
+ if (!trimmed) return '';
40
+ if (trimmed.length > DELIVERY_SYNC_ICON_MAX_LENGTH) return '';
41
+ // Line breaks would split the prefix from the text it introduces, and other
42
+ // control characters are invisible in the settings field.
43
+ if (CONTROL_CHARACTER.test(trimmed)) return '';
44
+ return trimmed;
45
+ }
46
+
47
+ function booleanOr(value, fallback) {
48
+ return typeof value === 'boolean' ? value : fallback;
49
+ }
50
+
51
+ /**
52
+ * Normalize one complete settings document body. Missing fields fall back to
53
+ * the defaults so a document written by an older build still loads; a value
54
+ * that is not an object at all returns null, which the store treats as damage.
55
+ */
56
+ export function normalizeDeliverySyncSettings(value) {
57
+ if (!isRecord(value)) return null;
58
+ return Object.freeze({
59
+ mirrorUserInput: booleanOr(value.mirrorUserInput, DEFAULT_DELIVERY_SYNC_SETTINGS.mirrorUserInput),
60
+ deliverModelAnswers: booleanOr(
61
+ value.deliverModelAnswers,
62
+ DEFAULT_DELIVERY_SYNC_SETTINGS.deliverModelAnswers,
63
+ ),
64
+ inputIcon: normalizeDeliverySyncIcon(value.inputIcon),
65
+ modelIcon: normalizeDeliverySyncIcon(value.modelIcon),
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Whether both delivery switches are off. This is the one predicate for
71
+ * silencing a Session's targets: the coordinator's target path and a channel's
72
+ * own mirror (the Feishu process card) both consult it, so "both off means this
73
+ * chat receives nothing" holds for every path that follows a Session.
74
+ *
75
+ * A value that cannot be normalized counts as off, so a damaged document fails
76
+ * closed here as it does in the coordinator.
77
+ */
78
+ export function deliverySwitchesOff(value) {
79
+ const settings = normalizeDeliverySyncSettings(value) ?? DEFAULT_DELIVERY_SYNC_SETTINGS;
80
+ return settings.mirrorUserInput === false && settings.deliverModelAnswers === false;
81
+ }
82
+
83
+ /**
84
+ * Apply a partial update (one RPC `set` payload) to the stored settings.
85
+ * Only the fields actually present are applied, so the settings page can save
86
+ * one row at a time without echoing back a stale snapshot of the others.
87
+ */
88
+ export function applyDeliverySyncPatch(current, patch) {
89
+ const base = normalizeDeliverySyncSettings(current) ?? DEFAULT_DELIVERY_SYNC_SETTINGS;
90
+ if (!isRecord(patch)) return base;
91
+ const next = { ...base };
92
+ if (Object.hasOwn(patch, 'mirrorUserInput') && typeof patch.mirrorUserInput === 'boolean') {
93
+ next.mirrorUserInput = patch.mirrorUserInput;
94
+ }
95
+ if (Object.hasOwn(patch, 'deliverModelAnswers') && typeof patch.deliverModelAnswers === 'boolean') {
96
+ next.deliverModelAnswers = patch.deliverModelAnswers;
97
+ }
98
+ for (const field of ['inputIcon', 'modelIcon']) {
99
+ if (Object.hasOwn(patch, field) && typeof patch[field] === 'string') {
100
+ next[field] = normalizeDeliverySyncIcon(patch[field]);
101
+ }
102
+ }
103
+ return Object.freeze(next);
104
+ }
105
+
106
+ /** Whether a payload carries only fields this document understands. */
107
+ export function deliverySyncPatchKeys(patch) {
108
+ if (!isRecord(patch)) return null;
109
+ const keys = Object.keys(patch);
110
+ const known = Object.keys(DEFAULT_DELIVERY_SYNC_SETTINGS);
111
+ return keys.every((key) => known.includes(key)) ? keys : null;
112
+ }
113
+
114
+ /**
115
+ * Render one delivered message body. A non-empty icon is separated from the
116
+ * text by a blank line so the prefix reads as a label rather than as part of
117
+ * the sentence.
118
+ */
119
+ export function withDeliverySyncIcon(icon, text) {
120
+ const normalized = normalizeDeliverySyncIcon(icon);
121
+ return normalized ? `${normalized}\n\n${text}` : text;
122
+ }
@@ -134,7 +134,12 @@ export function normalizeDiagnosticDetails(value) {
134
134
  if (Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599) result.httpStatus = value.httpStatus;
135
135
  const provider = typeof value.providerCode === 'number' && Number.isSafeInteger(value.providerCode)
136
136
  ? String(value.providerCode) : value.providerCode;
137
- if (typeof provider === 'string' && /^-?\d{1,12}$/.test(provider)) result.providerCode = provider;
137
+ // A provider code is either a numeric platform error code or an uppercase
138
+ // token such as PI_AI_ERROR. The token form used to be dropped here, so a
139
+ // turn failure that carried one reached the user as an unknown error with no
140
+ // service code at all, and the copied diagnostics named no cause either.
141
+ if (typeof provider === 'string'
142
+ && (/^-?\d{1,12}$/u.test(provider) || /^[A-Z][A-Z0-9_]{1,63}$/u.test(provider))) result.providerCode = provider;
138
143
  if (typeof value.pluginVersion === 'string' && /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.pluginVersion)
139
144
  && value.pluginVersion.length <= 64) result.pluginVersion = value.pluginVersion;
140
145
  if (['succeeded', 'failed', 'not-attempted', 'unknown'].includes(value.rollback)) result.rollback = value.rollback;
@@ -0,0 +1,79 @@
1
+ import { appendFileSync, mkdirSync, renameSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ /**
6
+ * One durable line per failed turn, so the reference id a user quotes back can
7
+ * be looked up after the fact.
8
+ *
9
+ * The console line the bridge already writes carries the same id, but a console
10
+ * line only exists while somebody captures stdout (`dsh` started from a
11
+ * terminal, a log collector). For a desktop app started from the dock there is
12
+ * no captured stream at all, so a `MF-…` id in a chat notice had nothing on disk
13
+ * to match it against — the id was, in practice, untraceable. This module keeps
14
+ * that record next to the other `.dsh-im` state.
15
+ *
16
+ * The file is best-effort by design: a failure to log must never mask the
17
+ * failure being reported to the user, so every filesystem error is swallowed.
18
+ */
19
+
20
+ const LOG_DIRECTORY = '.dsh-im';
21
+ const LOG_NAME = 'failures.jsonl';
22
+ /** Keep one previous generation; a chatty week must not grow the file forever. */
23
+ const MAX_LOG_BYTES = 2 * 1024 * 1024;
24
+ const TOKEN_SHAPE = /bot\d+:[A-Za-z0-9_-]{20,}/gu;
25
+
26
+ function resolveDshHome(dshHome) {
27
+ return dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
28
+ }
29
+
30
+ /** Absolute path of the failure log for one DSH home. */
31
+ export function failureLogPath({ dshHome } = {}) {
32
+ return join(resolveDshHome(dshHome), LOG_DIRECTORY, LOG_NAME);
33
+ }
34
+
35
+ function rotateIfNeeded(file) {
36
+ try {
37
+ if (statSync(file).size < MAX_LOG_BYTES) return;
38
+ renameSync(file, `${file}.1`);
39
+ } catch {
40
+ // Missing file, or a race with another writer: appending still works.
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Append one classified failure to the durable log.
46
+ *
47
+ * @param {object} failure - the object `classifyMessageFailure` returned.
48
+ * @param {object} [options]
49
+ * @param {string|null} [options.channel] - channel key, e.g. `feishu`.
50
+ * @param {string} [options.dshHome] - overrides `DSH_HOME`.
51
+ * @param {object|null} [options.details] - classified diagnostic details.
52
+ * @param {number} [options.at] - event time in epoch milliseconds.
53
+ * @returns {boolean} true when the line reached the file.
54
+ */
55
+ export function appendFailureLog(failure, { channel = null, dshHome, details = null, at = Date.now() } = {}) {
56
+ if (!failure || typeof failure !== 'object') return false;
57
+ const referenceId = typeof failure.referenceId === 'string' ? failure.referenceId : '';
58
+ if (!referenceId) return false;
59
+ try {
60
+ const file = failureLogPath({ dshHome });
61
+ mkdirSync(dirname(file), { recursive: true });
62
+ rotateIfNeeded(file);
63
+ const record = {
64
+ referenceId,
65
+ code: failure.code ?? null,
66
+ reason: failure.reason ?? null,
67
+ channel,
68
+ at: Number.isFinite(failure.at) ? failure.at : at,
69
+ // The provider code is what explains a MODEL_STREAM: STREAM_CLOSED versus
70
+ // MALFORMED_RESPONSE. `details` carries it when classification found it.
71
+ ...(details && typeof details === 'object' ? { details } : {}),
72
+ };
73
+ const line = JSON.stringify(record).replace(TOKEN_SHAPE, 'bot<redacted>');
74
+ appendFileSync(file, `${line}\n`, { encoding: 'utf8', mode: 0o600 });
75
+ return true;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }