@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.
- package/PROACTIVE_DELIVERY.en.md +33 -9
- package/PROACTIVE_DELIVERY.md +33 -9
- package/README.en.md +6 -3
- package/README.md +7 -4
- package/lib/client.js +582 -130
- package/lib/index.js +325 -325
- package/package.json +1 -1
- package/plugin-src/client/delivery-settings.js +2 -0
- package/plugin-src/client/delivery-sync-settings.js +269 -0
- package/plugin-src/client/global-settings.js +45 -7
- package/plugin-src/client/i18n-ru.js +27 -0
- package/plugin-src/client/i18n.js +27 -0
- package/plugin-src/client/index.js +17 -1
- package/plugin-src/client/model-setting.js +6 -3
- package/plugin-src/client/styles.js +16 -0
- package/plugin-src/host/channels/feishu/production.mjs +11 -27
- package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
- package/plugin-src/host/delivery-adapter.mjs +35 -20
- package/plugin-src/host/delivery-service.mjs +100 -1
- package/plugin-src/host/delivery-suggestions.mjs +28 -0
- package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
- package/plugin-src/host/host-language-rpc.mjs +16 -2
- package/plugin-src/host/host-language.mjs +29 -0
- package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
- package/plugin-src/host/index.mjs +23 -1
- package/plugin-src/host/session-sync-coordinator.mjs +288 -121
- package/plugin-src/host/session-sync-targets.mjs +71 -0
- package/plugin-src/host/sidebar-settings.mjs +1 -2
- package/plugin-src/host/update-rpc.mjs +1 -1
- package/plugin-src/management-rpc.mjs +25 -3
- package/scripts/verify-lan-management.mjs +58 -5
- package/scripts/verify-package.mjs +14 -5
- package/src/channels/email/email-runtime.mjs +27 -8
- package/src/channels/feishu/bridge.mjs +250 -3
- package/src/channels/qq/qq-bridge.mjs +9 -0
- package/src/channels/qq/state-store.mjs +42 -0
- package/src/channels/shared/action-card.mjs +83 -7
- package/src/channels/shared/bot-workspace-store.mjs +100 -8
- package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
- package/src/channels/shared/delivery-sync-settings.mjs +122 -0
- package/src/channels/shared/harness-client.mjs +148 -90
- package/src/channels/shared/i18n-en/diagnostics.mjs +7 -1
- package/src/channels/shared/i18n-en/feishu.mjs +3 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +6 -0
- package/src/channels/shared/i18n-ru/diagnostics.mjs +11 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +2 -0
- package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
- package/src/channels/shared/interface-language-store.mjs +49 -10
- package/src/channels/shared/interface-language.mjs +19 -1
- package/src/channels/shared/model-setting.mjs +6 -3
- package/src/channels/shared/workspace-session.mjs +13 -1
- package/src/channels/telegram/telegram-api.mjs +19 -1
|
@@ -135,6 +135,83 @@ export function actionCardStateText(status, texts = {}) {
|
|
|
135
135
|
* `maxEntries` cards are remembered (oldest is evicted first) and a new card in
|
|
136
136
|
* a conversation supersedes the previous live one.
|
|
137
137
|
*/
|
|
138
|
+
/** Telegram truncates button labels itself; we never want to rely on that. */
|
|
139
|
+
export const ACTION_CARD_BUTTON_TEXT_MAX = 60;
|
|
140
|
+
|
|
141
|
+
const UNSAFE_BUTTON_TEXT = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Make arbitrary text safe to put on a button.
|
|
145
|
+
*
|
|
146
|
+
* Workspace paths, session titles and preset labels all reach buttons, and any
|
|
147
|
+
* of them can carry control characters or newlines that would break the layout
|
|
148
|
+
* (or, for a bidirectional override, reorder what the user reads). Every card did
|
|
149
|
+
* this slightly differently — one of them skipped the control-character pass —
|
|
150
|
+
* so it lives here now and all of them call it.
|
|
151
|
+
*/
|
|
152
|
+
export function safeButtonText(value) {
|
|
153
|
+
if (typeof value !== 'string') return '';
|
|
154
|
+
return value.replace(UNSAFE_BUTTON_TEXT, ' ').replace(/\s+/gu, ' ').trim();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** `safeButtonText` plus the ellipsis every button label needs. */
|
|
158
|
+
export function truncateButtonText(value) {
|
|
159
|
+
const text = safeButtonText(value) || '•';
|
|
160
|
+
return text.length > ACTION_CARD_BUTTON_TEXT_MAX
|
|
161
|
+
? `${text.slice(0, ACTION_CARD_BUTTON_TEXT_MAX - 1)}…`
|
|
162
|
+
: text;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Longest we will wait for a rate-limited card operation.
|
|
167
|
+
*
|
|
168
|
+
* Telegram answers a throttled call with `retry_after` and expects the bot to
|
|
169
|
+
* come back then. A card edit is cheap and user-initiated (they just pressed a
|
|
170
|
+
* button), so waiting a few seconds and trying once more is much better than
|
|
171
|
+
* telling them "could not update, send the command again". Anything longer than
|
|
172
|
+
* this is not worth holding the turn open: the caller falls back.
|
|
173
|
+
*/
|
|
174
|
+
export const ACTION_CARD_RETRY_MAX_WAIT_MS = 5_000;
|
|
175
|
+
|
|
176
|
+
/** `retry_after` in milliseconds, read from either spelling Telegram uses. */
|
|
177
|
+
function rateLimitDelayMs(error) {
|
|
178
|
+
const value = error?.retry_after ?? error?.retryAfter;
|
|
179
|
+
const seconds = Number(value);
|
|
180
|
+
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
|
181
|
+
return Math.ceil(seconds * 1_000);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function isRateLimited(error) {
|
|
185
|
+
const code = Number(error?.providerCode ?? error?.status);
|
|
186
|
+
return code === 429 || error?.code === 'telegram-429';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Run one Telegram card operation, honouring a 429 exactly once.
|
|
191
|
+
*
|
|
192
|
+
* Every card paid for this separately before: a throttled edit surfaced as
|
|
193
|
+
* "无法更新卡片,请重新发送命令" even though Telegram had just said when to retry.
|
|
194
|
+
* This helper makes that recovery the default for all cards.
|
|
195
|
+
*
|
|
196
|
+
* Returns the operation's result, or rethrows the last error.
|
|
197
|
+
*/
|
|
198
|
+
export async function withActionCardRetry(operation, {
|
|
199
|
+
maxWaitMs = ACTION_CARD_RETRY_MAX_WAIT_MS,
|
|
200
|
+
} = {}) {
|
|
201
|
+
try {
|
|
202
|
+
return await operation();
|
|
203
|
+
} catch (error) {
|
|
204
|
+
const delay = isRateLimited(error) ? rateLimitDelayMs(error) : null;
|
|
205
|
+
// Only a short, explicit, known wait is worth taking; anything else is the
|
|
206
|
+
// caller's failure to report.
|
|
207
|
+
if (delay === null || delay > maxWaitMs) throw error;
|
|
208
|
+
// Deliberately NOT unref'd: a throttled retry is the only thing this call is
|
|
209
|
+
// waiting for, so the timer must keep the loop alive until it fires.
|
|
210
|
+
await new Promise((resolve) => { setTimeout(resolve, delay); });
|
|
211
|
+
return operation();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
138
215
|
export class ActionCardRegistry {
|
|
139
216
|
#ttlMs;
|
|
140
217
|
#maxEntries;
|
|
@@ -236,14 +313,13 @@ export class ActionCardRegistry {
|
|
|
236
313
|
}
|
|
237
314
|
|
|
238
315
|
/**
|
|
239
|
-
* Give a claimed card its keyboard back after
|
|
240
|
-
* still retryable (a transient RPC error, a
|
|
241
|
-
* card stays `claimed` forever and every later press is answered with "still
|
|
242
|
-
* submitting", so the only recovery is typing the decision as text.
|
|
316
|
+
* Give a claimed card its keyboard back after an operation that failed but is
|
|
317
|
+
* still retryable (a transient RPC error, a refused write).
|
|
243
318
|
*
|
|
244
|
-
*
|
|
245
|
-
*
|
|
246
|
-
*
|
|
319
|
+
* `settle()` only accepts terminal statuses, so a caller that wants the press
|
|
320
|
+
* to be available again has no other way back. Only a live claim can be
|
|
321
|
+
* released: a card already resolved, expired or superseded must stay dead, or
|
|
322
|
+
* a stale press could act on newer state. Returns the released entry, or null.
|
|
247
323
|
*/
|
|
248
324
|
releaseClaim(nonce) {
|
|
249
325
|
const entry = this.#lookup(nonce);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
1
2
|
import { ensurePresetWorkspace } from './preset-workspaces.mjs';
|
|
2
3
|
import { t } from './i18n.mjs';
|
|
3
4
|
import { normalizeBusyMessageMode, validateBusyMessageMode } from './message-mode.mjs';
|
|
@@ -25,7 +26,7 @@ import {
|
|
|
25
26
|
validateAccessPolicy,
|
|
26
27
|
} from './access-policy.mjs';
|
|
27
28
|
import { CONNECTION_TEST_STATE_IDENTITY } from './connection-test.mjs';
|
|
28
|
-
import { SESSION_BINDING_STATE_IDENTITY } from './session-binding-lock.mjs';
|
|
29
|
+
import { SESSION_BINDING_STATE_IDENTITY, withSessionBindingLock } from './session-binding-lock.mjs';
|
|
29
30
|
import {
|
|
30
31
|
DEFAULT_CONTEXT_ENHANCEMENT_CONFIG,
|
|
31
32
|
normalizeContextEnhancementConfig,
|
|
@@ -1781,6 +1782,12 @@ function unavailableModel() {
|
|
|
1781
1782
|
return error;
|
|
1782
1783
|
}
|
|
1783
1784
|
|
|
1785
|
+
function unavailableModelCatalog(cause) {
|
|
1786
|
+
const error = new Error(t('无法读取所选模型的列表,模型设置未保存,请重试。'), { cause });
|
|
1787
|
+
error.code = 'model-catalog-unavailable';
|
|
1788
|
+
return connectionStageError(error, 'status.read', undefined, { method: 'llm.models' });
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1784
1791
|
function assertCurrentBotScope(isCurrentScope) {
|
|
1785
1792
|
if (isCurrentScope()) return;
|
|
1786
1793
|
const error = new Error('找不到要修改的机器人。');
|
|
@@ -1998,8 +2005,18 @@ export function createBotWorkspaceScope(
|
|
|
1998
2005
|
const binding = dsBinding(key);
|
|
1999
2006
|
if (!binding) return null;
|
|
2000
2007
|
if (!dsBot) throw deliveryTargetError('ds-bot-unavailable', 'DS Bot 当前不可用,请检查插件状态。');
|
|
2001
|
-
|
|
2002
|
-
if (
|
|
2008
|
+
let bot = await dsBot.resolve(binding.dsBotId);
|
|
2009
|
+
if (typeof target.isSessionArchived === 'function' && (await target.isSessionArchived(bot.sessionId))) {
|
|
2010
|
+
for (let i = 0; i < 5; i += 1) {
|
|
2011
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
2012
|
+
const updated = await dsBot.resolve(binding.dsBotId).catch(() => null);
|
|
2013
|
+
if (updated && updated.sessionId !== bot.sessionId && !(await target.isSessionArchived(updated.sessionId))) {
|
|
2014
|
+
bot = updated;
|
|
2015
|
+
break;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
if (!(await target.sessionExists(bot.sessionId)) || (typeof target.isSessionArchived === 'function' && (await target.isSessionArchived(bot.sessionId)))) {
|
|
2003
2020
|
throw deliveryTargetError('ds-bot-not-found', 'DS Bot 的当前会话不可用。');
|
|
2004
2021
|
}
|
|
2005
2022
|
assertCurrentBotScope(isCurrentScope);
|
|
@@ -2492,8 +2509,10 @@ export function createBotWorkspaceScope(
|
|
|
2492
2509
|
// actual outcome even if a workspace switch commits concurrently.
|
|
2493
2510
|
return target[method](sessionId, ...args);
|
|
2494
2511
|
};
|
|
2512
|
+
let replySessionId = sessionId;
|
|
2495
2513
|
return Object.freeze({
|
|
2496
2514
|
sessionId,
|
|
2515
|
+
get replySessionId() { return replySessionId; },
|
|
2497
2516
|
async sessionExists(...args) {
|
|
2498
2517
|
if (!isCurrentSession()) return false;
|
|
2499
2518
|
const exists = await target.sessionExists(sessionId, ...args);
|
|
@@ -2531,7 +2550,15 @@ export function createBotWorkspaceScope(
|
|
|
2531
2550
|
}
|
|
2532
2551
|
// This is a Bot-wide setting. Never mutate only the IM session: DS
|
|
2533
2552
|
// Bot applies the choice to its own and group sessions as well.
|
|
2534
|
-
|
|
2553
|
+
const result = await dsBot.updateBotModel(dsBotId, selection, options);
|
|
2554
|
+
const selected = result?.selected;
|
|
2555
|
+
if (!selected || selected.reasoningEffort !== undefined) return result;
|
|
2556
|
+
// Without a level DS Bot sends none, and DSH runs the model's
|
|
2557
|
+
// default one: report the level the Session actually runs.
|
|
2558
|
+
const current = (await target.getSessionModels(sessionId, options))?.current;
|
|
2559
|
+
return current?.provider === selected.provider && current?.model === selected.model
|
|
2560
|
+
? { selected: { ...current } }
|
|
2561
|
+
: result;
|
|
2535
2562
|
},
|
|
2536
2563
|
isRunning(...args) {
|
|
2537
2564
|
return invokeCurrentSession('isSessionRunning', args, 'run-state check');
|
|
@@ -2566,7 +2593,63 @@ export function createBotWorkspaceScope(
|
|
|
2566
2593
|
throw workspaceSessionStale('DS Bot changed before this prompt started.');
|
|
2567
2594
|
}
|
|
2568
2595
|
}
|
|
2569
|
-
return target.ask(sessionId, ...args);
|
|
2596
|
+
if (!dsBotId) return target.ask(sessionId, ...args);
|
|
2597
|
+
const options = typeof args[1] === 'number' ? { timeoutMs: args[1] } : args[1] ?? {};
|
|
2598
|
+
const handoffResources = { stagedBatches: [] };
|
|
2599
|
+
let currentSessionId = sessionId;
|
|
2600
|
+
let promptRpcId;
|
|
2601
|
+
const assertStillBound = () => {
|
|
2602
|
+
options.signal?.throwIfAborted();
|
|
2603
|
+
if (!isCurrentSession()) {
|
|
2604
|
+
// This input was already accepted. A stale-session error here
|
|
2605
|
+
// would cause the outer loop to submit it again after unbind.
|
|
2606
|
+
throw new DOMException('DS Bot binding changed while awaiting a reply.', 'AbortError');
|
|
2607
|
+
}
|
|
2608
|
+
};
|
|
2609
|
+
for (;;) {
|
|
2610
|
+
try {
|
|
2611
|
+
const answer = promptRpcId
|
|
2612
|
+
? await target.waitForTransferredReply(currentSessionId, {
|
|
2613
|
+
...options, handoffResources, promptRpcId, assertCurrent: assertStillBound,
|
|
2614
|
+
})
|
|
2615
|
+
: await target.ask(sessionId, args[0], { ...options, handoffResources });
|
|
2616
|
+
if (promptRpcId) assertStillBound();
|
|
2617
|
+
replySessionId = currentSessionId;
|
|
2618
|
+
return answer;
|
|
2619
|
+
} catch (askError) {
|
|
2620
|
+
if (!dsBotId || !['session-archived', 'turn-blocked'].includes(askError?.code)) throw askError;
|
|
2621
|
+
assertStillBound();
|
|
2622
|
+
const evidence = extractConnectionEvidence(askError);
|
|
2623
|
+
const notSubmitted = evidence.details.submissionState === 'not-submitted';
|
|
2624
|
+
const accepted = askError.promptAccepted === true || evidence.details.submissionState === 'accepted';
|
|
2625
|
+
const originalRpcId = promptRpcId ?? askError.details?.promptRpcId ?? evidence.correlation.promptRpcId;
|
|
2626
|
+
// A failed submit can have an unknown outcome. Only explicit
|
|
2627
|
+
// pre-submit evidence permits replay; everything else needs
|
|
2628
|
+
// the durable identity of an accepted message to follow.
|
|
2629
|
+
if (!notSubmitted && (!accepted || !originalRpcId
|
|
2630
|
+
|| typeof target.waitForTransferredReply !== 'function')) throw askError;
|
|
2631
|
+
let fresh;
|
|
2632
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
2633
|
+
assertStillBound();
|
|
2634
|
+
fresh = await dsBot.resolve(dsBotId).catch(() => null);
|
|
2635
|
+
assertStillBound();
|
|
2636
|
+
if (fresh && fresh.sessionId !== currentSessionId) break;
|
|
2637
|
+
await delay(200, undefined, { signal: options.signal });
|
|
2638
|
+
}
|
|
2639
|
+
if (!fresh || fresh.sessionId === currentSessionId) throw askError;
|
|
2640
|
+
if (notSubmitted) throw workspaceSessionStale('DS Bot rolled over before this prompt was submitted.');
|
|
2641
|
+
currentSessionId = fresh.sessionId;
|
|
2642
|
+
promptRpcId = originalRpcId;
|
|
2643
|
+
await withSessionBindingLock(state, conversationKey, async () => {
|
|
2644
|
+
assertStillBound();
|
|
2645
|
+
await state.setSession(conversationKey, currentSessionId);
|
|
2646
|
+
assertStillBound();
|
|
2647
|
+
sessionGenerations.set(currentSessionId, {
|
|
2648
|
+
generation, conversationKey, conversationGeneration,
|
|
2649
|
+
});
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2570
2653
|
},
|
|
2571
2654
|
});
|
|
2572
2655
|
};
|
|
@@ -2745,9 +2828,18 @@ export function createWorkspaceAwareController(controller, {
|
|
|
2745
2828
|
error.code = 'workspace-bot-not-found';
|
|
2746
2829
|
throw error;
|
|
2747
2830
|
}
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2831
|
+
let catalog = null;
|
|
2832
|
+
if (model && modelCatalog) {
|
|
2833
|
+
try {
|
|
2834
|
+
catalog = await resolveModelCatalog(modelCatalog, { fresh: true, throwOnError: true });
|
|
2835
|
+
} catch (error) {
|
|
2836
|
+
if (error?.name === 'AbortError') throw error;
|
|
2837
|
+
throw unavailableModelCatalog(error);
|
|
2838
|
+
}
|
|
2839
|
+
if (catalog?.failures.some((failure) => failure.id === model.provider)) {
|
|
2840
|
+
throw unavailableModelCatalog();
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2751
2843
|
const entry = modelCatalogEntry(catalog, model);
|
|
2752
2844
|
if (model && (!modelCatalog || !entry)) {
|
|
2753
2845
|
throw unavailableModel();
|
|
@@ -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
|
+
}
|