@dsh-ray/assistant-delivery 0.3.2 → 0.3.4

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.
@@ -0,0 +1,1406 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { assistantT1PreferenceKeys, assistantT1PreferenceValues, } from '@dsh-ray/assistant-growth-contract';
3
+ export const CONFIG_CATEGORY_ORDER = Object.freeze([
4
+ 'conversation',
5
+ 'lark',
6
+ 'routing',
7
+ 'providers',
8
+ ]);
9
+ export const NEW_PROVIDER_SENTINEL = '__new__';
10
+ const DEFAULT_EFFORT_SENTINEL = '__default__';
11
+ const CREDENTIAL_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
12
+ const PROVIDER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
13
+ const LARK_NAMESPACE_PATTERN = /^dsh-ray-lark-channel(?:$|[:@])/u;
14
+ const TRAEX_NAMESPACE_PATTERN = /^dsh-ray-traex-acp-provider(?:$|[:@])/u;
15
+ const OWNER_CONSOLE_NAMESPACE_PATTERN = /^dsh-ray-owner-console(?:$|[:@])/u;
16
+ const DEFAULT_MODEL_NAMESPACE_PATTERN = /^agent-default-model(?:$|[:@])/u;
17
+ export const OWNER_CONSOLE_PROCESS_LOGS_KEY = 'showProcessLogs';
18
+ const PI_AI_NAMESPACE_PATTERN = /^llm-pi-ai(?:$|[:@])/u;
19
+ const DEEPSEEK_NAMESPACE_PATTERN = /^(?:dsh-llm-deepseek|deepseek-official)(?:$|[:@])/u;
20
+ const EXCLUDED_NAMESPACES = new Set([
21
+ 'kernel',
22
+ 'kernel.json',
23
+ 'assistant-policy',
24
+ 'dsh-ray-assistant-policy',
25
+ 'assistant-isolation',
26
+ 'dsh-ray-assistant-isolation',
27
+ 'assistant-actions',
28
+ 'dsh-ray-assistant-actions',
29
+ 'assistant-verifier',
30
+ 'dsh-ray-assistant-verifier',
31
+ 'credentials-keychain',
32
+ 'dsh-ray-credentials-keychain',
33
+ 'assistant-delivery',
34
+ 'dsh-ray-assistant-delivery',
35
+ ]);
36
+ const ALLOWED_LARK_UX_FIELDS = new Set([
37
+ 'showProgress',
38
+ 'progressDetails',
39
+ 'showBackgroundProgress',
40
+ 'statusReactions',
41
+ 'requireMentionInGroups',
42
+ 'groupTopicThreads',
43
+ 'maxTextBytes',
44
+ 'staleAfterMs',
45
+ ]);
46
+ const EXCLUDED_LARK_FIELDS = new Set([
47
+ 'enabled',
48
+ 'account',
49
+ 'tenant',
50
+ 'appId',
51
+ 'appSecretEnv',
52
+ 'credentialHandle',
53
+ 'secretSource',
54
+ 'credentialPurpose',
55
+ 'credentialLeaseMs',
56
+ 'domain',
57
+ 'handshakeTimeoutMs',
58
+ 'requestTimeoutMs',
59
+ 'imageDownloadTimeoutMs',
60
+ 'userQuestionTtlMs',
61
+ 'allowedCalendarIds',
62
+ ]);
63
+ const ALLOWED_TRAEX_FIELDS = new Set([
64
+ 'enabled',
65
+ 'agyEnabled',
66
+ 'cwdMode',
67
+ 'agyMode',
68
+ 'agyDisableTelemetry',
69
+ 'logDiagnostics',
70
+ ]);
71
+ const RESERVED_PI_AI_PROVIDER_IDS = new Set([
72
+ 'traex-agent',
73
+ 'agy-agent',
74
+ 'deepseek-official',
75
+ NEW_PROVIDER_SENTINEL,
76
+ ]);
77
+ export const PI_AI_SUPPORTED_APIS = Object.freeze([
78
+ 'openai-completions',
79
+ 'openai-responses',
80
+ 'anthropic-messages',
81
+ ]);
82
+ const T1_KEY_METADATA = Object.freeze({
83
+ 'response.verbosity': {
84
+ label: '回复详略度',
85
+ description: '控制日常回答的篇幅与信息密度',
86
+ defaultDisplay: 'balanced',
87
+ optionLabels: { concise: '简洁(concise)', balanced: '均衡(balanced)', detailed: '详细(detailed)' },
88
+ },
89
+ 'response.structure': {
90
+ label: '回复结构风格',
91
+ description: '控制回答的组织形式(段落或列表)',
92
+ defaultDisplay: 'mixed',
93
+ optionLabels: { prose: '自然段落(prose)', bullets: '要点列表(bullets)', mixed: '混合排版(mixed)' },
94
+ },
95
+ 'response.language': {
96
+ label: '默认回复语言',
97
+ description: '控制助手优先使用的语言',
98
+ defaultDisplay: 'zh-CN',
99
+ optionLabels: { 'zh-CN': '简体中文(zh-CN)', en: 'English(en)' },
100
+ },
101
+ 'response.explanation_depth': {
102
+ label: '解释深度',
103
+ description: '先给结论还是展开原理与步骤',
104
+ defaultDisplay: 'balanced',
105
+ optionLabels: { 'result-first': '结论优先(result-first)', balanced: '均衡(balanced)', tutorial: '教程展开(tutorial)' },
106
+ },
107
+ 'suggestion.frequency': {
108
+ label: '主动建议频率',
109
+ description: '控制完成任务后附带扩展建议的频率',
110
+ defaultDisplay: 'normal',
111
+ optionLabels: { low: '低频(low)', normal: '正常(normal)' },
112
+ },
113
+ 'recommendation.ranking': {
114
+ label: '记忆与推荐排序',
115
+ description: '控制上下文召回与候选排序倾向',
116
+ defaultDisplay: 'evidence',
117
+ optionLabels: { recency: '最近优先(recency)', familiarity: '熟悉度优先(familiarity)', evidence: '证据强度优先(evidence)' },
118
+ },
119
+ });
120
+ export const T1_TEXT_KEY_ALIASES = Object.freeze({
121
+ 'response.verbosity': 'response.verbosity',
122
+ verbosity: 'response.verbosity',
123
+ 'response.structure': 'response.structure',
124
+ structure: 'response.structure',
125
+ 'response.language': 'response.language',
126
+ language: 'response.language',
127
+ 'response.explanation_depth': 'response.explanation_depth',
128
+ explanation_depth: 'response.explanation_depth',
129
+ explanation: 'response.explanation_depth',
130
+ 'suggestion.frequency': 'suggestion.frequency',
131
+ suggestion_frequency: 'suggestion.frequency',
132
+ 'recommendation.ranking': 'recommendation.ranking',
133
+ recommendation_ranking: 'recommendation.ranking',
134
+ });
135
+ export function isExcludedConfigTarget(target) {
136
+ const normalized = target.trim().toLowerCase();
137
+ if (normalized === '')
138
+ return true;
139
+ if (normalized.includes('kernel.json') || normalized.startsWith('kernel/') || normalized.startsWith('kernel.')) {
140
+ return true;
141
+ }
142
+ const baseNs = normalized.split(/[:@.]/u)[0] ?? normalized;
143
+ return EXCLUDED_NAMESPACES.has(normalized) || EXCLUDED_NAMESPACES.has(baseNs);
144
+ }
145
+ export function isAllowedConfigField(namespace, field) {
146
+ if (isExcludedConfigTarget(namespace))
147
+ return false;
148
+ if (LARK_NAMESPACE_PATTERN.test(namespace)) {
149
+ return !EXCLUDED_LARK_FIELDS.has(field) && ALLOWED_LARK_UX_FIELDS.has(field);
150
+ }
151
+ if (TRAEX_NAMESPACE_PATTERN.test(namespace)) {
152
+ return ALLOWED_TRAEX_FIELDS.has(field);
153
+ }
154
+ if (OWNER_CONSOLE_NAMESPACE_PATTERN.test(namespace)) {
155
+ return field === OWNER_CONSOLE_PROCESS_LOGS_KEY;
156
+ }
157
+ if (DEFAULT_MODEL_NAMESPACE_PATTERN.test(namespace)) {
158
+ return field === 'provider' || field === 'model' || field === 'reasoningEffort';
159
+ }
160
+ if (DEEPSEEK_NAMESPACE_PATTERN.test(namespace)) {
161
+ return field === 'baseURL' || field === 'thinking' || field === 'reasoningEffort' || field === 'maxTokens';
162
+ }
163
+ if (PI_AI_NAMESPACE_PATTERN.test(namespace)) {
164
+ return field === 'providers';
165
+ }
166
+ return false;
167
+ }
168
+ export function redactConfigSecret(text, secret) {
169
+ if (typeof secret !== 'string')
170
+ return text;
171
+ const trimmed = secret.trim();
172
+ if (trimmed === '')
173
+ return text;
174
+ const candidates = new Set([secret, trimmed]);
175
+ const ordered = [...candidates].sort((a, b) => b.length - a.length);
176
+ let out = text;
177
+ for (const candidate of ordered) {
178
+ out = out.split(candidate).join('[REDACTED]');
179
+ const hexLower = Buffer.from(candidate, 'utf8').toString('hex');
180
+ const hexUpper = hexLower.toUpperCase();
181
+ if (hexLower.length >= 8) {
182
+ out = out.split(hexLower).join('[REDACTED]');
183
+ if (hexUpper !== hexLower)
184
+ out = out.split(hexUpper).join('[REDACTED]');
185
+ }
186
+ }
187
+ return out;
188
+ }
189
+ export function deriveCredentialRefName(providerId) {
190
+ const trimmed = providerId.trim();
191
+ if (trimmed === 'deepseek-official')
192
+ return 'DEEPSEEK_API_KEY';
193
+ const normalized = trimmed
194
+ .replaceAll(/[^A-Za-z0-9]+/gu, '_')
195
+ .replaceAll(/^_+|_+$/gu, '')
196
+ .toUpperCase();
197
+ return `${normalized || 'PROVIDER'}_API_KEY`;
198
+ }
199
+ export function validateCredentialRefName(raw) {
200
+ const trimmed = raw.trim();
201
+ if (!CREDENTIAL_REF_PATTERN.test(trimmed)) {
202
+ throw new Error(`凭据引用名无效(须为合法环境变量名,如 OPENROUTER_API_KEY):${trimmed}`);
203
+ }
204
+ return trimmed;
205
+ }
206
+ export function validateApiKeyInput(raw) {
207
+ const trimmed = raw.trim();
208
+ if (trimmed.length === 0) {
209
+ throw new Error('API Key 不能为空');
210
+ }
211
+ if (/^bearer\s+/iu.test(trimmed)) {
212
+ throw new Error('API Key 不应包含 "Bearer " 前缀,请只输入 Key 本身');
213
+ }
214
+ if (!/^[\x21-\x7E]+$/u.test(trimmed)) {
215
+ throw new Error('API Key 包含空白、换行或非 ASCII 可打印字符,请检查后重试');
216
+ }
217
+ return trimmed;
218
+ }
219
+ function asRecord(value) {
220
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
221
+ ? value
222
+ : {};
223
+ }
224
+ function findSettingsEntry(entries, pattern) {
225
+ return entries.find(entry => !isExcludedConfigTarget(entry.ns) && pattern.test(entry.ns));
226
+ }
227
+ function boolSelect(key, label, description, currentValue, trueLabel = '开启(true)', falseLabel = '关闭(false)') {
228
+ return {
229
+ kind: 'select',
230
+ key,
231
+ label,
232
+ description,
233
+ options: [
234
+ { value: 'true', label: trueLabel },
235
+ { value: 'false', label: falseLabel },
236
+ ],
237
+ currentValue: currentValue ? 'true' : 'false',
238
+ };
239
+ }
240
+ function parseBoolString(raw, label) {
241
+ const normalized = raw.trim().toLowerCase();
242
+ if (normalized === 'true' || normalized === '1' || normalized === 'on' || normalized === 'yes')
243
+ return true;
244
+ if (normalized === 'false' || normalized === '0' || normalized === 'off' || normalized === 'no')
245
+ return false;
246
+ throw new Error(`${label} 必须为 true 或 false`);
247
+ }
248
+ function parseBoundedInt(raw, min, max, label) {
249
+ const trimmed = raw.trim();
250
+ if (!/^-?\d+$/u.test(trimmed))
251
+ throw new Error(`${label} 必须是整数`);
252
+ const parsed = Number(trimmed);
253
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
254
+ throw new Error(`${label} 必须在 ${min} 到 ${max} 之间`);
255
+ }
256
+ return parsed;
257
+ }
258
+ function validateHttpUrl(raw, label) {
259
+ const trimmed = raw.trim();
260
+ if (trimmed === '' || /[\s\p{Cc}]/u.test(trimmed)) {
261
+ throw new Error(`${label} 不能为空或包含空白/控制字符`);
262
+ }
263
+ let parsed;
264
+ try {
265
+ parsed = new URL(trimmed);
266
+ }
267
+ catch {
268
+ throw new Error(`${label} 不是合法的 URL`);
269
+ }
270
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
271
+ throw new Error(`${label} 仅支持 http:// 或 https://`);
272
+ }
273
+ return trimmed;
274
+ }
275
+ function formatCredentialBadge(info, available) {
276
+ if (!available)
277
+ return '凭证服务未挂载';
278
+ if (info === undefined || !info.configured)
279
+ return '未配置';
280
+ const masked = typeof info.masked === 'string' && info.masked.trim() !== '' ? info.masked : '***';
281
+ const source = typeof info.source === 'string' && info.source.trim() !== '' ? ` · ${info.source}` : '';
282
+ return `已配置(${masked}${source})`;
283
+ }
284
+ export async function buildConfigPickerSnapshot(input) {
285
+ const descriptors = input.settings?.describe({ redactSecrets: true }) ?? [];
286
+ // 1. Conversation (T1 Preferences via assistantPreferenceLearning + optional owner-console showProcessLogs)
287
+ const conversationCategory = buildConversationCategory(input, descriptors, input.settings !== undefined);
288
+ // 2. Lark UX (dsh-ray-lark-channel)
289
+ const larkCategory = buildLarkCategory(descriptors, input.settings !== undefined, input.categoryNotices?.lark);
290
+ // 3. Routing (agent-default-model + dsh-ray-traex-acp-provider + optional dsh-llm-deepseek)
291
+ const routingCategory = await buildRoutingCategory({
292
+ descriptors,
293
+ hasSettings: input.settings !== undefined,
294
+ ...(input.agentDefaultModel === undefined ? {} : { agentDefaultModel: input.agentDefaultModel }),
295
+ ...(input.llm === undefined ? {} : { llm: input.llm }),
296
+ ...(input.categoryNotices?.routing === undefined ? {} : { notice: input.categoryNotices.routing }),
297
+ });
298
+ // 4. Providers & Credentials (STRICT DM-ONLY)
299
+ const providersCategory = await buildProvidersCategory({
300
+ conversationKind: input.conversationKind,
301
+ descriptors,
302
+ hasSettings: input.settings !== undefined,
303
+ ...(input.credentials === undefined ? {} : { credentials: input.credentials }),
304
+ ...(input.activeProviderId === undefined ? {} : { activeProviderId: input.activeProviderId }),
305
+ ...(input.categoryNotices?.providers === undefined ? {} : { notice: input.categoryNotices.providers }),
306
+ });
307
+ const categories = [
308
+ conversationCategory,
309
+ larkCategory,
310
+ routingCategory,
311
+ providersCategory,
312
+ ];
313
+ const resolvedActiveProviderId = input.conversationKind === 'dm'
314
+ ? providersCategory.activeProviderId
315
+ : undefined;
316
+ const digestInput = {
317
+ bindingVersion: input.bindingVersion,
318
+ sessionId: input.sessionId,
319
+ conversationKind: input.conversationKind,
320
+ categories: categories.map(cat => ({
321
+ id: cat.id,
322
+ available: cat.available,
323
+ namespace: cat.namespace ?? null,
324
+ revision: cat.revision ?? null,
325
+ fields: cat.fields.map(f => ({
326
+ key: f.key,
327
+ val: f.kind === 'select' ? f.currentValue : (f.inputType === 'password' ? (f.statusBadge ?? '') : (f.currentValue ?? '')),
328
+ })),
329
+ providers: cat.providers?.map(p => ({
330
+ id: p.id,
331
+ ref: p.credentialRef ?? null,
332
+ masked: p.credentialMasked ?? null,
333
+ configured: p.credentialConfigured ?? false,
334
+ fields: p.fields.map(f => ({
335
+ key: f.key,
336
+ val: f.kind === 'select' ? f.currentValue : (f.inputType === 'password' ? (f.statusBadge ?? '') : (f.currentValue ?? '')),
337
+ })),
338
+ })),
339
+ })),
340
+ };
341
+ const stateHash = createHash('sha256')
342
+ .update('assistant-delivery-config-picker-state-v1\0')
343
+ .update(JSON.stringify(digestInput))
344
+ .digest('hex');
345
+ return {
346
+ operationId: input.operationId,
347
+ issuedAt: input.issuedAt,
348
+ expiresAt: input.expiresAt,
349
+ bindingVersion: input.bindingVersion,
350
+ sessionId: input.sessionId,
351
+ conversationKind: input.conversationKind,
352
+ activeCategory: input.activeCategory,
353
+ ...(resolvedActiveProviderId === undefined ? {} : { activeProviderId: resolvedActiveProviderId }),
354
+ stateHash,
355
+ categories,
356
+ };
357
+ }
358
+ function buildConversationCategory(input, descriptors, hasSettings) {
359
+ const explain = input.learningExplainReceipt;
360
+ const health = input.preferenceLearning?.health?.();
361
+ const activeValues = new Map();
362
+ if (explain !== undefined && explain.outcome === 'applied' && explain.explanation !== undefined) {
363
+ for (const item of explain.explanation) {
364
+ if (item.state === 'active')
365
+ activeValues.set(item.key, item.value);
366
+ }
367
+ }
368
+ else if (input.preferenceLearning?.hostReview !== undefined && input.principalLineage !== undefined) {
369
+ try {
370
+ const review = input.preferenceLearning.hostReview({
371
+ workspace: input.workspace,
372
+ preset: input.preset,
373
+ principal: input.principalId,
374
+ principalLineage: input.principalLineage,
375
+ operationId: `cfg-view:${input.operationId}`,
376
+ limit: 50,
377
+ });
378
+ for (const h of review.hypotheses) {
379
+ if (h.state === 'active')
380
+ activeValues.set(h.key, h.value);
381
+ }
382
+ }
383
+ catch {
384
+ // Fall back cleanly if hostReview is unavailable or unauthorized for read.
385
+ }
386
+ }
387
+ const appliedExplain = explain?.outcome === 'applied' ? explain : undefined;
388
+ const prefAvailable = appliedExplain !== undefined || explain !== undefined || input.preferenceLearning !== undefined;
389
+ const ownerConsoleEntry = hasSettings ? findSettingsEntry(descriptors, OWNER_CONSOLE_NAMESPACE_PATTERN) : undefined;
390
+ const available = prefAvailable || ownerConsoleEntry !== undefined;
391
+ const mode = appliedExplain?.state?.mode ?? (health?.enabled === false ? 'disabled' : 'active');
392
+ const collectionMode = appliedExplain?.state?.collectionMode;
393
+ let subtitle = '调整助手回复风格与偏好(立即通过 T1 偏好账本生效)';
394
+ let notice = input.categoryNotices?.conversation;
395
+ if (!prefAvailable && ownerConsoleEntry !== undefined) {
396
+ subtitle = '偏好学习服务(preference-learning)当前未挂载,仅可配置桌面端过程日志开关';
397
+ notice ??= '偏好学习服务(preference-learning)当前未挂载,仅可修改桌面端过程日志开关。';
398
+ }
399
+ else if (!available) {
400
+ subtitle = '偏好学习服务(preference-learning)当前未挂载';
401
+ }
402
+ else if (mode === 'disabled') {
403
+ subtitle = '偏好学习服务当前已停用(enabled=false)';
404
+ notice ??= '偏好学习服务当前已停用;提交修改可能不会立即激活。';
405
+ }
406
+ else if (collectionMode === 'paused' || mode === 'paused') {
407
+ subtitle = '偏好学习当前处于暂停状态(可发送 /learning resume 恢复)';
408
+ notice ??= '当前偏好学习已暂停,新提交仅在恢复后激活。';
409
+ }
410
+ const t1Fields = assistantT1PreferenceKeys.map(key => {
411
+ const meta = T1_KEY_METADATA[key];
412
+ const options = assistantT1PreferenceValues[key].map(val => ({
413
+ value: val,
414
+ label: meta.optionLabels[val] ?? val,
415
+ }));
416
+ const currentValue = activeValues.get(key) ?? meta.defaultDisplay;
417
+ return {
418
+ kind: 'select',
419
+ key,
420
+ label: meta.label,
421
+ description: meta.description,
422
+ options,
423
+ currentValue,
424
+ };
425
+ });
426
+ const showProcessLogsField = ownerConsoleEntry === undefined
427
+ ? undefined
428
+ : boolSelect(OWNER_CONSOLE_PROCESS_LOGS_KEY, '桌面端过程日志(COT / 工具细节)', '开启后在桌面端对话中保留可展开的思考与工具执行过程;关闭时默认隐藏仅保留简洁状态', asRecord(ownerConsoleEntry.value)[OWNER_CONSOLE_PROCESS_LOGS_KEY] === true, '开启展示(true)', '默认隐藏(false)');
429
+ const fields = showProcessLogsField === undefined
430
+ ? t1Fields
431
+ : prefAvailable
432
+ ? [...t1Fields, showProcessLogsField]
433
+ : [showProcessLogsField];
434
+ return {
435
+ id: 'conversation',
436
+ label: '对话偏好',
437
+ subtitle,
438
+ available,
439
+ ...(ownerConsoleEntry === undefined ? {} : { namespace: ownerConsoleEntry.ns, revision: ownerConsoleEntry.revision }),
440
+ ...(available ? {} : { unavailableReason: 'assistantPreferenceLearning 服务未挂载' }),
441
+ ...(notice === undefined ? {} : { notice }),
442
+ fields,
443
+ };
444
+ }
445
+ function buildLarkCategory(descriptors, hasSettings, notice) {
446
+ const entry = findSettingsEntry(descriptors, LARK_NAMESPACE_PATTERN);
447
+ if (!hasSettings || entry === undefined) {
448
+ return {
449
+ id: 'lark',
450
+ label: '飞书体验',
451
+ subtitle: '实时调整飞书进度展示、群聊 @ 触发与消息限额(热更新不断连)',
452
+ available: false,
453
+ unavailableReason: hasSettings ? 'dsh-ray-lark-channel 未挂载或未处于活动状态' : 'Host settings 服务未挂载',
454
+ ...(notice === undefined ? {} : { notice }),
455
+ fields: [],
456
+ };
457
+ }
458
+ const value = asRecord(entry.value);
459
+ const showProgress = value['showProgress'] !== false;
460
+ const progressDetails = value['progressDetails'] === 'off' ? 'off' : 'direct';
461
+ const showBackgroundProgress = value['showBackgroundProgress'] === true;
462
+ const statusReactions = value['statusReactions'] !== false;
463
+ const requireMentionInGroups = value['requireMentionInGroups'] !== false;
464
+ const groupTopicThreads = value['groupTopicThreads'] === true;
465
+ const maxTextBytes = typeof value['maxTextBytes'] === 'number' && Number.isSafeInteger(value['maxTextBytes'])
466
+ ? value['maxTextBytes']
467
+ : 65_536;
468
+ const staleAfterMs = typeof value['staleAfterMs'] === 'number' && Number.isSafeInteger(value['staleAfterMs'])
469
+ ? value['staleAfterMs']
470
+ : 300_000;
471
+ const fields = [
472
+ boolSelect('showProgress', '执行进度卡片', '在回复过程中展示实时执行进度卡', showProgress),
473
+ {
474
+ kind: 'select',
475
+ key: 'progressDetails',
476
+ label: '私聊工具执行详情',
477
+ description: '控制私聊进度卡是否展示具体工具调用摘要',
478
+ options: [
479
+ { value: 'direct', label: '私聊展示详情(direct)' },
480
+ { value: 'off', label: '关闭详情(off)' },
481
+ ],
482
+ currentValue: progressDetails,
483
+ },
484
+ boolSelect('showBackgroundProgress', '后台任务进度展示', '是否展示后台 Goal 轮次的非终态进度', showBackgroundProgress),
485
+ boolSelect('statusReactions', '消息状态表情反馈', '收到消息和回复完成后自动添加状态表情', statusReactions),
486
+ boolSelect('requireMentionInGroups', '群聊必须 @ 机器人', '开启后群聊仅响应 @ 机器人的消息', requireMentionInGroups),
487
+ boolSelect('groupTopicThreads', '群聊按话题串隔离会话', '开启后每个飞书群话题 thread_id 作为独立会话', groupTopicThreads),
488
+ {
489
+ kind: 'input',
490
+ key: 'maxTextBytes',
491
+ label: '单条消息最大字节(1..1048576)',
492
+ description: '超出该字节预算将触发自动压缩或文本附件发送',
493
+ inputType: 'number',
494
+ currentValue: String(maxTextBytes),
495
+ placeholder: '65536',
496
+ maxLength: 16,
497
+ },
498
+ {
499
+ kind: 'input',
500
+ key: 'staleAfterMs',
501
+ label: '过期消息忽略阈值(毫秒 1000..86400000)',
502
+ description: '超过该延迟的积压飞书事件将被安全跳过',
503
+ inputType: 'number',
504
+ currentValue: String(staleAfterMs),
505
+ placeholder: '300000',
506
+ maxLength: 16,
507
+ },
508
+ ];
509
+ return {
510
+ id: 'lark',
511
+ label: '飞书体验',
512
+ subtitle: '实时热更新飞书通道交互参数(不重启 WebSocket 长连接)',
513
+ available: true,
514
+ namespace: entry.ns,
515
+ revision: entry.revision,
516
+ ...(notice === undefined ? {} : { notice }),
517
+ fields,
518
+ };
519
+ }
520
+ async function buildRoutingCategory(input) {
521
+ const defaultEntry = findSettingsEntry(input.descriptors, DEFAULT_MODEL_NAMESPACE_PATTERN);
522
+ const traexEntry = findSettingsEntry(input.descriptors, TRAEX_NAMESPACE_PATTERN);
523
+ const deepseekEntry = findSettingsEntry(input.descriptors, DEEPSEEK_NAMESPACE_PATTERN);
524
+ const fields = [];
525
+ // Default Model fields
526
+ let currentProvider = '';
527
+ let currentModel = '';
528
+ let currentEffort = '';
529
+ if (input.agentDefaultModel !== undefined) {
530
+ try {
531
+ const sel = input.agentDefaultModel.currentSelection();
532
+ currentProvider = sel.provider;
533
+ currentModel = sel.model;
534
+ currentEffort = sel.reasoningEffort === undefined ? '' : String(sel.reasoningEffort);
535
+ }
536
+ catch {
537
+ // Fallback to settings descriptor below.
538
+ }
539
+ }
540
+ if (currentProvider === '' && defaultEntry !== undefined) {
541
+ const val = asRecord(defaultEntry.value);
542
+ if (typeof val['provider'] === 'string')
543
+ currentProvider = val['provider'];
544
+ if (typeof val['model'] === 'string')
545
+ currentModel = val['model'];
546
+ if (typeof val['reasoningEffort'] === 'string')
547
+ currentEffort = val['reasoningEffort'];
548
+ }
549
+ const defaultRouteAvailable = defaultEntry !== undefined || input.agentDefaultModel !== undefined;
550
+ if (defaultRouteAvailable) {
551
+ const routeOptions = [];
552
+ const seenRoutes = new Set();
553
+ const addRoute = (provider, model, label) => {
554
+ const route = `${provider}/${model}`;
555
+ if (seenRoutes.has(route) || routeOptions.length >= 60)
556
+ return;
557
+ seenRoutes.add(route);
558
+ routeOptions.push({ value: route, label: label ?? route });
559
+ };
560
+ if (currentProvider !== '' && currentModel !== '') {
561
+ addRoute(currentProvider, currentModel, `${currentProvider}/${currentModel}(当前默认)`);
562
+ }
563
+ if (input.llm !== undefined) {
564
+ const providers = input.llm.listProviders();
565
+ for (const p of providers) {
566
+ try {
567
+ const models = await input.llm.listModels(p.id);
568
+ for (const m of models.slice(0, 15)) {
569
+ addRoute(p.id, m.id, `${p.name} / ${m.name === m.id ? m.id : `${m.name} (${m.id})`}`);
570
+ }
571
+ }
572
+ catch {
573
+ // Ignore providers whose model directory probe fails.
574
+ }
575
+ }
576
+ }
577
+ if (routeOptions.length > 0) {
578
+ fields.push({
579
+ kind: 'select',
580
+ key: 'defaultRoute',
581
+ label: '全局默认模型(新会话生效)',
582
+ description: '配置新建会话与未指定会话覆盖时的默认 provider/model',
583
+ options: routeOptions,
584
+ currentValue: currentProvider !== '' && currentModel !== ''
585
+ ? `${currentProvider}/${currentModel}`
586
+ : routeOptions[0].value,
587
+ });
588
+ }
589
+ const effortOptions = [
590
+ { value: DEFAULT_EFFORT_SENTINEL, label: '默认(由模型决定)' },
591
+ { value: 'low', label: '低(low)' },
592
+ { value: 'medium', label: '中(medium)' },
593
+ { value: 'high', label: '高(high)' },
594
+ { value: 'max', label: '最高(max)' },
595
+ ];
596
+ if (currentEffort !== '' && !effortOptions.some(opt => opt.value === currentEffort)) {
597
+ effortOptions.push({ value: currentEffort, label: currentEffort });
598
+ }
599
+ fields.push({
600
+ kind: 'select',
601
+ key: 'defaultReasoningEffort',
602
+ label: '默认 Reasoning Effort 档位',
603
+ description: '控制支持推理强度的默认模型档位',
604
+ options: effortOptions,
605
+ currentValue: currentEffort === '' ? DEFAULT_EFFORT_SENTINEL : currentEffort,
606
+ });
607
+ }
608
+ // TraeX / Antigravity ACP volatile flags
609
+ if (traexEntry !== undefined) {
610
+ const val = asRecord(traexEntry.value);
611
+ fields.push(boolSelect('acpEnabled', 'TraeX 本地路由(traex-agent)', '实时注册或注销 TraeX ACP 编码模型路由', val['enabled'] === true), boolSelect('acpAgyEnabled', 'Antigravity 本地路由(agy-agent)', '实时注册或注销 Antigravity ACP 编码模型路由', val['agyEnabled'] === true), {
612
+ kind: 'select',
613
+ key: 'acpCwdMode',
614
+ label: 'ACP 工作目录模式(cwdMode)',
615
+ description: '使用当前 DSH 会话工作区或固定配置目录',
616
+ options: [
617
+ { value: 'session', label: '跟随会话工作区(session)' },
618
+ { value: 'exact', label: '固定 cwd(exact)' },
619
+ ],
620
+ currentValue: val['cwdMode'] === 'exact' ? 'exact' : 'session',
621
+ }, {
622
+ kind: 'select',
623
+ key: 'acpAgyMode',
624
+ label: 'Antigravity 会话模式(agyMode)',
625
+ description: '控制 agy acp session/new 后的权限模式',
626
+ options: [
627
+ { value: 'default', label: '默认执行模式(default)' },
628
+ { value: 'plan', label: '只读规划模式(plan)' },
629
+ ],
630
+ currentValue: val['agyMode'] === 'plan' ? 'plan' : 'default',
631
+ }, boolSelect('acpAgyDisableTelemetry', '禁用 Antigravity 遥测', '向 agy acp 传递 --disable-telemetry', val['agyDisableTelemetry'] !== false), boolSelect('acpLogDiagnostics', '记录 ACP stderr 诊断日志', '在宿主日志中输出脱敏后的子进程 stderr 尾部', val['logDiagnostics'] === true));
632
+ }
633
+ // Optional DeepSeek settings when mounted
634
+ if (deepseekEntry !== undefined) {
635
+ const val = asRecord(deepseekEntry.value);
636
+ if (val['thinking'] === 'enabled' || val['thinking'] === 'disabled' || val['thinking'] === undefined) {
637
+ fields.push({
638
+ kind: 'select',
639
+ key: 'deepseekThinking',
640
+ label: 'DeepSeek 思考模式(thinking)',
641
+ description: '控制 deepseek-official 默认思考模式',
642
+ options: [
643
+ { value: 'enabled', label: '开启(enabled)' },
644
+ { value: 'disabled', label: '关闭(disabled)' },
645
+ ],
646
+ currentValue: val['thinking'] === 'disabled' ? 'disabled' : 'enabled',
647
+ });
648
+ }
649
+ const dsEffort = typeof val['reasoningEffort'] === 'string' ? val['reasoningEffort'] : DEFAULT_EFFORT_SENTINEL;
650
+ fields.push({
651
+ kind: 'select',
652
+ key: 'deepseekReasoningEffort',
653
+ label: 'DeepSeek Reasoning Effort',
654
+ options: [
655
+ { value: DEFAULT_EFFORT_SENTINEL, label: '默认' },
656
+ { value: 'off', label: '关闭(off)' },
657
+ { value: 'low', label: '低(low)' },
658
+ { value: 'high', label: '高(high)' },
659
+ { value: 'max', label: '最高(max)' },
660
+ ],
661
+ currentValue: dsEffort,
662
+ });
663
+ }
664
+ const available = fields.length > 0;
665
+ return {
666
+ id: 'routing',
667
+ label: '默认模型与路由',
668
+ subtitle: '修改全局默认模型及本地 ACP 编码路由开关(实时生效)',
669
+ available,
670
+ ...(available ? {} : {
671
+ unavailableReason: input.hasSettings
672
+ ? 'agent-default-model 与 dsh-ray-traex-acp-provider 均未挂载'
673
+ : 'Host settings 与默认模型服务均未挂载',
674
+ }),
675
+ ...(defaultEntry !== undefined
676
+ ? { namespace: defaultEntry.ns, revision: defaultEntry.revision }
677
+ : traexEntry !== undefined
678
+ ? { namespace: traexEntry.ns, revision: traexEntry.revision }
679
+ : {}),
680
+ ...(input.notice === undefined ? {} : { notice: input.notice }),
681
+ fields,
682
+ };
683
+ }
684
+ async function describeRefSafe(credentials, refName) {
685
+ if (credentials === undefined || !CREDENTIAL_REF_PATTERN.test(refName))
686
+ return undefined;
687
+ try {
688
+ return await credentials.describe(refName);
689
+ }
690
+ catch {
691
+ return undefined;
692
+ }
693
+ }
694
+ async function buildProvidersCategory(input) {
695
+ if (input.conversationKind !== 'dm') {
696
+ return {
697
+ id: 'providers',
698
+ label: 'Provider 与密钥',
699
+ subtitle: '仅限私聊(DM)查看与修改模型 Provider 及 API Key',
700
+ available: false,
701
+ dmOnly: true,
702
+ unavailableReason: '安全限制:模型 Provider 与 API Key 配置仅限在机器人私聊(DM)中进行,群聊已自动屏蔽。',
703
+ ...(input.notice === undefined ? {} : { notice: input.notice }),
704
+ fields: [],
705
+ };
706
+ }
707
+ const piAiEntry = findSettingsEntry(input.descriptors, PI_AI_NAMESPACE_PATTERN);
708
+ const deepseekEntry = findSettingsEntry(input.descriptors, DEEPSEEK_NAMESPACE_PATTERN);
709
+ const providersMap = asRecord(asRecord(piAiEntry?.value)['providers']);
710
+ const providerItems = [];
711
+ // Existing llm-pi-ai providers
712
+ for (const [providerId, rawProfile] of Object.entries(providersMap)) {
713
+ if (providerItems.length >= 25)
714
+ break;
715
+ const profile = asRecord(rawProfile);
716
+ const displayName = typeof profile['displayName'] === 'string' && profile['displayName'].trim() !== ''
717
+ ? profile['displayName'].trim()
718
+ : providerId;
719
+ const api = typeof profile['api'] === 'string' && PI_AI_SUPPORTED_APIS.includes(profile['api'])
720
+ ? profile['api']
721
+ : 'openai-completions';
722
+ const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : '';
723
+ const apiKeyEnv = typeof profile['apiKeyEnv'] === 'string' && CREDENTIAL_REF_PATTERN.test(profile['apiKeyEnv'])
724
+ ? profile['apiKeyEnv']
725
+ : deriveCredentialRefName(providerId);
726
+ const modelsArr = Array.isArray(profile['models']) ? profile['models'] : [];
727
+ const modelIds = modelsArr
728
+ .map(entry => typeof entry === 'string' ? entry : asRecord(entry)['id'])
729
+ .filter((id) => typeof id === 'string' && id.trim() !== '')
730
+ .join(', ');
731
+ const credInfo = await describeRefSafe(input.credentials, apiKeyEnv);
732
+ providerItems.push({
733
+ id: providerId,
734
+ label: `${displayName} [${providerId}]`,
735
+ credentialRef: apiKeyEnv,
736
+ credentialConfigured: credInfo?.configured === true,
737
+ ...(credInfo?.masked === undefined ? {} : { credentialMasked: credInfo.masked }),
738
+ credentialWritable: credInfo?.writable ?? (input.credentials !== undefined),
739
+ fields: [
740
+ {
741
+ kind: 'input',
742
+ key: 'displayName',
743
+ label: '显示名称',
744
+ inputType: 'text',
745
+ currentValue: displayName,
746
+ maxLength: 120,
747
+ },
748
+ {
749
+ kind: 'select',
750
+ key: 'api',
751
+ label: '接口协议(api)',
752
+ options: [
753
+ { value: 'openai-completions', label: 'OpenAI Chat Completions' },
754
+ { value: 'openai-responses', label: 'OpenAI Responses' },
755
+ { value: 'anthropic-messages', label: 'Anthropic Messages' },
756
+ ],
757
+ currentValue: api,
758
+ },
759
+ {
760
+ kind: 'input',
761
+ key: 'baseURL',
762
+ label: 'Base URL',
763
+ description: '完整接口基础地址(https://...)',
764
+ inputType: 'text',
765
+ currentValue: baseURL,
766
+ placeholder: 'https://api.example.com/v1',
767
+ maxLength: 512,
768
+ },
769
+ {
770
+ kind: 'input',
771
+ key: 'models',
772
+ label: '模型 ID 列表(逗号分隔)',
773
+ description: '至少一个模型 ID,例如 gpt-4.1, gpt-4.1-mini',
774
+ inputType: 'text',
775
+ currentValue: modelIds,
776
+ placeholder: 'gpt-4.1, gpt-4.1-mini',
777
+ maxLength: 1_024,
778
+ },
779
+ {
780
+ kind: 'input',
781
+ key: 'apiKeyEnv',
782
+ label: '凭据引用名(apiKeyEnv)',
783
+ description: '写入 $DSH_HOME/.credentials.yaml 的环境变量键名',
784
+ inputType: 'text',
785
+ currentValue: apiKeyEnv,
786
+ placeholder: 'PROVIDER_API_KEY',
787
+ maxLength: 128,
788
+ },
789
+ {
790
+ kind: 'input',
791
+ key: 'apiKey',
792
+ label: 'API Key(只写不回显)',
793
+ description: '留空则保持当前存储密钥不变;提交后写入 0600 凭据文件',
794
+ inputType: 'password',
795
+ placeholder: '留空保持不变,或粘贴新 API Key',
796
+ statusBadge: formatCredentialBadge(credInfo, input.credentials !== undefined),
797
+ maxLength: 512,
798
+ ...(input.credentials === undefined ? { unavailableReason: '凭证服务未挂载' } : {}),
799
+ },
800
+ ],
801
+ });
802
+ }
803
+ // Built-in DeepSeek official credential & optional baseURL
804
+ if (deepseekEntry !== undefined || input.credentials !== undefined) {
805
+ const credInfo = await describeRefSafe(input.credentials, 'DEEPSEEK_API_KEY');
806
+ const dsFields = [];
807
+ if (deepseekEntry !== undefined) {
808
+ const dsValue = asRecord(deepseekEntry.value);
809
+ dsFields.push({
810
+ kind: 'input',
811
+ key: 'baseURL',
812
+ label: 'DeepSeek Base URL',
813
+ inputType: 'text',
814
+ currentValue: typeof dsValue['baseURL'] === 'string' ? dsValue['baseURL'] : 'https://api.deepseek.com',
815
+ maxLength: 512,
816
+ });
817
+ }
818
+ dsFields.push({
819
+ kind: 'input',
820
+ key: 'apiKey',
821
+ label: 'DEEPSEEK_API_KEY(只写不回显)',
822
+ description: '留空则保持当前密钥不变;更新后立即对下一次调用生效',
823
+ inputType: 'password',
824
+ placeholder: '留空保持不变,或粘贴新 DEEPSEEK_API_KEY',
825
+ statusBadge: formatCredentialBadge(credInfo, input.credentials !== undefined),
826
+ maxLength: 512,
827
+ ...(input.credentials === undefined ? { unavailableReason: '凭证服务未挂载' } : {}),
828
+ });
829
+ providerItems.push({
830
+ id: 'deepseek-official',
831
+ label: 'DeepSeek Official [deepseek-official]',
832
+ credentialRef: 'DEEPSEEK_API_KEY',
833
+ credentialConfigured: credInfo?.configured === true,
834
+ ...(credInfo?.masked === undefined ? {} : { credentialMasked: credInfo.masked }),
835
+ credentialWritable: credInfo?.writable ?? (input.credentials !== undefined),
836
+ fields: dsFields,
837
+ });
838
+ }
839
+ // Always offer "+ New Custom Provider" when llm-pi-ai is mounted
840
+ if (piAiEntry !== undefined) {
841
+ providerItems.push({
842
+ id: NEW_PROVIDER_SENTINEL,
843
+ label: '+ 新增自定义 Provider(llm-pi-ai)',
844
+ isNew: true,
845
+ credentialWritable: input.credentials !== undefined,
846
+ fields: [
847
+ {
848
+ kind: 'input',
849
+ key: 'providerId',
850
+ label: '新 Provider ID(必填)',
851
+ description: '如 openrouter、my-gateway(字母数字及 ._-)',
852
+ inputType: 'text',
853
+ currentValue: '',
854
+ placeholder: 'my-provider',
855
+ required: true,
856
+ maxLength: 64,
857
+ },
858
+ {
859
+ kind: 'input',
860
+ key: 'displayName',
861
+ label: '显示名称(可选)',
862
+ inputType: 'text',
863
+ currentValue: '',
864
+ placeholder: 'My Provider',
865
+ maxLength: 120,
866
+ },
867
+ {
868
+ kind: 'select',
869
+ key: 'api',
870
+ label: '接口协议(api)',
871
+ options: [
872
+ { value: 'openai-completions', label: 'OpenAI Chat Completions' },
873
+ { value: 'openai-responses', label: 'OpenAI Responses' },
874
+ { value: 'anthropic-messages', label: 'Anthropic Messages' },
875
+ ],
876
+ currentValue: 'openai-completions',
877
+ },
878
+ {
879
+ kind: 'input',
880
+ key: 'baseURL',
881
+ label: 'Base URL(必填)',
882
+ description: '例如 https://openrouter.ai/api/v1',
883
+ inputType: 'text',
884
+ currentValue: '',
885
+ placeholder: 'https://api.example.com/v1',
886
+ required: true,
887
+ maxLength: 512,
888
+ },
889
+ {
890
+ kind: 'input',
891
+ key: 'models',
892
+ label: '模型 ID 列表(必填,逗号分隔)',
893
+ inputType: 'text',
894
+ currentValue: '',
895
+ placeholder: 'gpt-4.1, gpt-4.1-mini',
896
+ required: true,
897
+ maxLength: 1_024,
898
+ },
899
+ {
900
+ kind: 'input',
901
+ key: 'apiKeyEnv',
902
+ label: '凭据引用名(可选,默认自动派生)',
903
+ inputType: 'text',
904
+ currentValue: '',
905
+ placeholder: 'MY_PROVIDER_API_KEY',
906
+ maxLength: 128,
907
+ },
908
+ {
909
+ kind: 'input',
910
+ key: 'apiKey',
911
+ label: 'API Key(只写不回显)',
912
+ description: '仅写入本地 $DSH_HOME/.credentials.yaml(0600),绝不回显',
913
+ inputType: 'password',
914
+ placeholder: '粘贴 API Key(可选,稍后补写)',
915
+ statusBadge: input.credentials === undefined ? '凭证服务未挂载' : '新增时可填写',
916
+ maxLength: 512,
917
+ ...(input.credentials === undefined ? { unavailableReason: '凭证服务未挂载' } : {}),
918
+ },
919
+ ],
920
+ });
921
+ }
922
+ const activeProvider = providerItems.find(item => item.id === input.activeProviderId) ?? providerItems[0];
923
+ const available = providerItems.length > 0 && (piAiEntry !== undefined || input.credentials !== undefined);
924
+ return {
925
+ id: 'providers',
926
+ label: 'Provider 与密钥',
927
+ subtitle: '管理 llm-pi-ai 自定义模型网关与 API Key(仅私聊 · 只写不回显)',
928
+ available,
929
+ dmOnly: true,
930
+ ...(available ? {} : {
931
+ unavailableReason: input.hasSettings || input.credentials !== undefined
932
+ ? 'llm-pi-ai 与凭证服务当前均未挂载'
933
+ : 'Host settings 与 credentials 服务未挂载',
934
+ }),
935
+ ...(piAiEntry !== undefined
936
+ ? { namespace: piAiEntry.ns, revision: piAiEntry.revision }
937
+ : deepseekEntry !== undefined
938
+ ? { namespace: deepseekEntry.ns, revision: deepseekEntry.revision }
939
+ : {}),
940
+ ...(input.notice === undefined ? {} : { notice: input.notice }),
941
+ ...(activeProvider === undefined ? {} : { activeProviderId: activeProvider.id }),
942
+ fields: activeProvider?.fields ?? [],
943
+ providers: providerItems,
944
+ };
945
+ }
946
+ export function readOwnerConsoleShowProcessLogs(settings) {
947
+ if (settings === undefined)
948
+ return undefined;
949
+ const descriptors = settings.describe({ redactSecrets: true });
950
+ const entry = findSettingsEntry(descriptors, OWNER_CONSOLE_NAMESPACE_PATTERN);
951
+ if (entry === undefined)
952
+ return undefined;
953
+ return asRecord(entry.value)[OWNER_CONSOLE_PROCESS_LOGS_KEY] === true;
954
+ }
955
+ export function parseT1ConversationSelections(pairs) {
956
+ const selections = [];
957
+ for (const [rawKey, rawValue] of Object.entries(pairs)) {
958
+ const canonicalKey = Object.hasOwn(T1_TEXT_KEY_ALIASES, rawKey)
959
+ ? T1_TEXT_KEY_ALIASES[rawKey]
960
+ : undefined;
961
+ if (canonicalKey === undefined) {
962
+ return { ok: false, message: `不支持的对话偏好字段:${rawKey}` };
963
+ }
964
+ const allowedValues = assistantT1PreferenceValues[canonicalKey];
965
+ const cleanVal = rawValue.trim();
966
+ if (allowedValues === undefined || !allowedValues.includes(cleanVal)) {
967
+ return {
968
+ ok: false,
969
+ message: `字段 ${canonicalKey} 不支持取值 “${cleanVal}”(可选:${allowedValues?.join(' / ') ?? ''})`,
970
+ };
971
+ }
972
+ selections.push({
973
+ preferenceKey: canonicalKey,
974
+ candidateValue: cleanVal,
975
+ });
976
+ }
977
+ if (selections.length === 0) {
978
+ return { ok: false, message: '未检测到可修改的对话偏好字段' };
979
+ }
980
+ return { ok: true, selections };
981
+ }
982
+ export function validateOwnerConsoleConversationMutation(input) {
983
+ if (input.settings === undefined) {
984
+ return { ok: false, message: 'Host settings 服务未挂载,无法修改桌面端过程日志开关' };
985
+ }
986
+ const descriptors = input.settings.describe({ redactSecrets: true });
987
+ const entry = findSettingsEntry(descriptors, OWNER_CONSOLE_NAMESPACE_PATTERN);
988
+ if (entry === undefined) {
989
+ return { ok: false, message: 'dsh-ray-owner-console 当前未挂载或未启用,无法修改桌面端过程日志开关' };
990
+ }
991
+ if (!isAllowedConfigField(entry.ns, OWNER_CONSOLE_PROCESS_LOGS_KEY)) {
992
+ return { ok: false, message: '拒绝修改受保护的 owner-console 字段' };
993
+ }
994
+ const expected = input.expectedRevisions?.[entry.ns];
995
+ if (expected !== undefined && expected !== entry.revision) {
996
+ return { ok: false, conflict: true, message: '桌面端过程日志配置已被其他操作更新,请确认最新值后重试' };
997
+ }
998
+ const rawVal = input.values[OWNER_CONSOLE_PROCESS_LOGS_KEY];
999
+ if (rawVal === undefined) {
1000
+ return { ok: false, message: '缺少 showProcessLogs 参数值' };
1001
+ }
1002
+ try {
1003
+ const nextBool = parseBoolString(rawVal, OWNER_CONSOLE_PROCESS_LOGS_KEY);
1004
+ const prevBool = asRecord(entry.value)[OWNER_CONSOLE_PROCESS_LOGS_KEY] === true;
1005
+ return { ok: true, entry, nextBool, prevBool };
1006
+ }
1007
+ catch (error) {
1008
+ return {
1009
+ ok: false,
1010
+ message: error instanceof Error ? error.message : String(error),
1011
+ };
1012
+ }
1013
+ }
1014
+ export async function applyOwnerConsoleConversationMutation(input) {
1015
+ const validated = validateOwnerConsoleConversationMutation(input);
1016
+ if (!validated.ok)
1017
+ return validated;
1018
+ try {
1019
+ await input.settings.mutate(validated.entry.ns, [{ op: 'set', path: [OWNER_CONSOLE_PROCESS_LOGS_KEY], value: validated.nextBool }], validated.entry.revision);
1020
+ return {
1021
+ ok: true,
1022
+ changed: validated.prevBool !== validated.nextBool,
1023
+ message: validated.nextBool
1024
+ ? '桌面端思考与工具过程日志已开启(实时生效)'
1025
+ : '桌面端思考与工具过程日志已关闭(默认隐藏,实时生效)',
1026
+ };
1027
+ }
1028
+ catch (error) {
1029
+ const isConflict = typeof error === 'object' && error !== null
1030
+ && (error.code === 'SETTINGS_CONFLICT'
1031
+ || error.name === 'SettingsConflictError');
1032
+ return {
1033
+ ok: false,
1034
+ ...(isConflict ? { conflict: true } : {}),
1035
+ message: isConflict
1036
+ ? '桌面端过程日志配置已被其他操作更新,已为您刷新最新状态,请确认后重试'
1037
+ : (error instanceof Error ? error.message : String(error)),
1038
+ };
1039
+ }
1040
+ }
1041
+ export async function applyNonPreferenceConfigMutation(input) {
1042
+ if (input.category === 'providers' && input.conversationKind !== 'dm') {
1043
+ return { ok: false, message: '安全限制:模型 Provider 与 API Key 配置仅限在机器人私聊(DM)中使用' };
1044
+ }
1045
+ const descriptors = input.settings?.describe({ redactSecrets: true }) ?? [];
1046
+ try {
1047
+ if (input.category === 'lark') {
1048
+ if (input.settings === undefined) {
1049
+ return { ok: false, message: 'Host settings 服务未挂载,无法保存飞书体验参数' };
1050
+ }
1051
+ const entry = findSettingsEntry(descriptors, LARK_NAMESPACE_PATTERN);
1052
+ if (entry === undefined) {
1053
+ return { ok: false, message: 'dsh-ray-lark-channel 当前未挂载或未启用,无法保存' };
1054
+ }
1055
+ const expected = input.expectedRevisions?.[entry.ns];
1056
+ if (expected !== undefined && expected !== entry.revision) {
1057
+ return { ok: false, conflict: true, message: '飞书配置已被其他操作更新,请确认最新值后重试' };
1058
+ }
1059
+ const ops = [];
1060
+ for (const [key, rawVal] of Object.entries(input.values)) {
1061
+ if (!isAllowedConfigField(entry.ns, key)) {
1062
+ return { ok: false, message: `拒绝修改受保护或不支持的字段:${key}` };
1063
+ }
1064
+ if (key === 'showProgress' || key === 'showBackgroundProgress' || key === 'statusReactions'
1065
+ || key === 'requireMentionInGroups' || key === 'groupTopicThreads') {
1066
+ ops.push({ op: 'set', path: [key], value: parseBoolString(rawVal, key) });
1067
+ }
1068
+ else if (key === 'progressDetails') {
1069
+ const val = rawVal.trim();
1070
+ if (val !== 'off' && val !== 'direct') {
1071
+ return { ok: false, message: 'progressDetails 仅支持 direct 或 off' };
1072
+ }
1073
+ ops.push({ op: 'set', path: [key], value: val });
1074
+ }
1075
+ else if (key === 'maxTextBytes') {
1076
+ ops.push({ op: 'set', path: [key], value: parseBoundedInt(rawVal, 1, 1_048_576, 'maxTextBytes') });
1077
+ }
1078
+ else if (key === 'staleAfterMs') {
1079
+ ops.push({ op: 'set', path: [key], value: parseBoundedInt(rawVal, 1_000, 86_400_000, 'staleAfterMs') });
1080
+ }
1081
+ }
1082
+ if (ops.length === 0)
1083
+ return { ok: false, message: '未检测到可修改的飞书参数' };
1084
+ await input.settings.mutate(entry.ns, ops, entry.revision);
1085
+ return { ok: true, message: '飞书体验参数已保存并实时生效(长连接未中断)' };
1086
+ }
1087
+ if (input.category === 'routing') {
1088
+ const updates = [];
1089
+ const values = input.values;
1090
+ // Default model update
1091
+ const routeValue = values['defaultRoute']?.trim();
1092
+ const explicitProvider = values['provider']?.trim();
1093
+ const explicitModel = values['model']?.trim();
1094
+ let nextProvider = explicitProvider;
1095
+ let nextModel = explicitModel;
1096
+ if (routeValue !== undefined && routeValue !== '') {
1097
+ const slash = routeValue.indexOf('/');
1098
+ if (slash <= 0 || slash === routeValue.length - 1) {
1099
+ return { ok: false, message: '默认模型格式无效,应为 provider/model' };
1100
+ }
1101
+ nextProvider = routeValue.slice(0, slash);
1102
+ nextModel = routeValue.slice(slash + 1);
1103
+ }
1104
+ const effortValue = values['defaultReasoningEffort'] ?? values['reasoningEffort'];
1105
+ if (nextProvider !== undefined || nextModel !== undefined || effortValue !== undefined) {
1106
+ const defaultEntry = findSettingsEntry(descriptors, DEFAULT_MODEL_NAMESPACE_PATTERN);
1107
+ const current = input.agentDefaultModel?.currentSelection();
1108
+ const currentRec = asRecord(defaultEntry?.value);
1109
+ const resolvedProvider = nextProvider ?? current?.provider ?? (typeof currentRec['provider'] === 'string' ? currentRec['provider'] : '');
1110
+ const resolvedModel = nextModel ?? current?.model ?? (typeof currentRec['model'] === 'string' ? currentRec['model'] : '');
1111
+ if (!PROVIDER_ID_PATTERN.test(resolvedProvider) || resolvedModel.trim() === '' || /[\p{Cc}]/u.test(resolvedModel)) {
1112
+ return { ok: false, message: '默认模型的 provider 或 model 无效' };
1113
+ }
1114
+ const rawEffort = effortValue === undefined
1115
+ ? (current?.reasoningEffort === undefined ? '' : String(current.reasoningEffort))
1116
+ : effortValue.trim();
1117
+ const resolvedEffort = rawEffort === DEFAULT_EFFORT_SENTINEL || rawEffort === '' ? undefined : rawEffort;
1118
+ if (resolvedEffort !== undefined && (resolvedEffort.length > 128 || /[\p{Cc}\s]/u.test(resolvedEffort))) {
1119
+ return { ok: false, message: 'reasoningEffort 格式无效' };
1120
+ }
1121
+ if (defaultEntry !== undefined && input.settings !== undefined) {
1122
+ const ops = [
1123
+ { op: 'set', path: ['provider'], value: resolvedProvider },
1124
+ { op: 'set', path: ['model'], value: resolvedModel },
1125
+ resolvedEffort === undefined
1126
+ ? { op: 'unset', path: ['reasoningEffort'] }
1127
+ : { op: 'set', path: ['reasoningEffort'], value: resolvedEffort },
1128
+ ];
1129
+ await input.settings.mutate(defaultEntry.ns, ops, defaultEntry.revision);
1130
+ updates.push(`默认模型 ${resolvedProvider}/${resolvedModel}`);
1131
+ }
1132
+ else if (input.agentDefaultModel !== undefined) {
1133
+ await input.agentDefaultModel.saveSelection({
1134
+ provider: resolvedProvider,
1135
+ model: resolvedModel,
1136
+ ...(resolvedEffort === undefined ? {} : { reasoningEffort: resolvedEffort }),
1137
+ });
1138
+ updates.push(`默认模型 ${resolvedProvider}/${resolvedModel}`);
1139
+ }
1140
+ else {
1141
+ return { ok: false, message: 'agent-default-model 服务未挂载,无法保存默认模型' };
1142
+ }
1143
+ }
1144
+ // TraeX / Antigravity ACP volatile flags
1145
+ const acpOps = [];
1146
+ const acpFieldMap = [
1147
+ ['acpEnabled', 'enabled', 'bool'],
1148
+ ['enabled', 'enabled', 'bool'],
1149
+ ['acpAgyEnabled', 'agyEnabled', 'bool'],
1150
+ ['agyEnabled', 'agyEnabled', 'bool'],
1151
+ ['acpCwdMode', 'cwdMode', 'cwdMode'],
1152
+ ['cwdMode', 'cwdMode', 'cwdMode'],
1153
+ ['acpAgyMode', 'agyMode', 'agyMode'],
1154
+ ['agyMode', 'agyMode', 'agyMode'],
1155
+ ['acpAgyDisableTelemetry', 'agyDisableTelemetry', 'bool'],
1156
+ ['agyDisableTelemetry', 'agyDisableTelemetry', 'bool'],
1157
+ ['acpLogDiagnostics', 'logDiagnostics', 'bool'],
1158
+ ['logDiagnostics', 'logDiagnostics', 'bool'],
1159
+ ];
1160
+ const seenAcp = new Set();
1161
+ for (const [formKey, targetKey, kind] of acpFieldMap) {
1162
+ const rawVal = values[formKey];
1163
+ if (rawVal === undefined || seenAcp.has(targetKey))
1164
+ continue;
1165
+ seenAcp.add(targetKey);
1166
+ if (kind === 'bool') {
1167
+ acpOps.push({ op: 'set', path: [targetKey], value: parseBoolString(rawVal, formKey) });
1168
+ }
1169
+ else if (kind === 'cwdMode') {
1170
+ const val = rawVal.trim();
1171
+ if (val !== 'session' && val !== 'exact')
1172
+ return { ok: false, message: 'cwdMode 仅支持 session 或 exact' };
1173
+ acpOps.push({ op: 'set', path: [targetKey], value: val });
1174
+ }
1175
+ else {
1176
+ const val = rawVal.trim();
1177
+ if (val !== 'default' && val !== 'plan')
1178
+ return { ok: false, message: 'agyMode 仅支持 default 或 plan' };
1179
+ acpOps.push({ op: 'set', path: [targetKey], value: val });
1180
+ }
1181
+ }
1182
+ if (acpOps.length > 0) {
1183
+ if (input.settings === undefined)
1184
+ return { ok: false, message: 'Host settings 服务未挂载' };
1185
+ const traexEntry = findSettingsEntry(descriptors, TRAEX_NAMESPACE_PATTERN);
1186
+ if (traexEntry === undefined) {
1187
+ return { ok: false, message: 'dsh-ray-traex-acp-provider 未挂载,无法保存 ACP 路由配置' };
1188
+ }
1189
+ await input.settings.mutate(traexEntry.ns, acpOps, traexEntry.revision);
1190
+ updates.push('本地 ACP 路由');
1191
+ }
1192
+ // Optional DeepSeek settings
1193
+ const dsOps = [];
1194
+ if (values['deepseekThinking'] !== undefined) {
1195
+ const val = values['deepseekThinking'].trim();
1196
+ if (val !== 'enabled' && val !== 'disabled')
1197
+ return { ok: false, message: 'thinking 仅支持 enabled 或 disabled' };
1198
+ dsOps.push({ op: 'set', path: ['thinking'], value: val });
1199
+ }
1200
+ if (values['deepseekReasoningEffort'] !== undefined) {
1201
+ const val = values['deepseekReasoningEffort'].trim();
1202
+ if (val === DEFAULT_EFFORT_SENTINEL || val === '')
1203
+ dsOps.push({ op: 'unset', path: ['reasoningEffort'] });
1204
+ else if (val === 'off' || val === 'low' || val === 'high' || val === 'max') {
1205
+ dsOps.push({ op: 'set', path: ['reasoningEffort'], value: val });
1206
+ }
1207
+ else {
1208
+ return { ok: false, message: 'DeepSeek reasoningEffort 仅支持 off/low/high/max' };
1209
+ }
1210
+ }
1211
+ if (dsOps.length > 0) {
1212
+ if (input.settings === undefined)
1213
+ return { ok: false, message: 'Host settings 服务未挂载' };
1214
+ const dsEntry = findSettingsEntry(descriptors, DEEPSEEK_NAMESPACE_PATTERN);
1215
+ if (dsEntry === undefined)
1216
+ return { ok: false, message: 'dsh-llm-deepseek 未挂载' };
1217
+ await input.settings.mutate(dsEntry.ns, dsOps, dsEntry.revision);
1218
+ updates.push('DeepSeek 默认参数');
1219
+ }
1220
+ if (updates.length === 0)
1221
+ return { ok: false, message: '未检测到可修改的模型路由参数' };
1222
+ return { ok: true, message: `已保存并实时生效:${updates.join('、')}` };
1223
+ }
1224
+ // Category: 'providers' (DM-only already enforced at entry)
1225
+ const values = input.values;
1226
+ const targetProviderId = input.targetProviderId?.trim();
1227
+ const formProviderId = values['providerId']?.trim();
1228
+ if (targetProviderId !== undefined && targetProviderId !== '' && targetProviderId !== NEW_PROVIDER_SENTINEL
1229
+ && formProviderId !== undefined && formProviderId !== '' && formProviderId !== targetProviderId) {
1230
+ return {
1231
+ ok: false,
1232
+ message: `当前正在编辑 Provider「${targetProviderId}」,不能将 Provider ID 修改为「${formProviderId}」;如需新增请先切换至「+ 新增自定义 Provider」`,
1233
+ };
1234
+ }
1235
+ const selectedTarget = targetProviderId !== undefined && targetProviderId !== ''
1236
+ ? targetProviderId
1237
+ : (formProviderId ?? '');
1238
+ const rawSecret = input.ephemeralSecret?.trim() ?? '';
1239
+ if (selectedTarget === 'deepseek-official') {
1240
+ const hasBaseUrlUpdate = values['baseURL'] !== undefined && values['baseURL'].trim() !== '';
1241
+ let dsEntry;
1242
+ let validatedUrl;
1243
+ if (hasBaseUrlUpdate) {
1244
+ dsEntry = findSettingsEntry(descriptors, DEEPSEEK_NAMESPACE_PATTERN);
1245
+ if (dsEntry === undefined || input.settings === undefined) {
1246
+ return { ok: false, message: 'dsh-llm-deepseek 未挂载,无法修改 baseURL' };
1247
+ }
1248
+ validatedUrl = validateHttpUrl(values['baseURL'], 'DeepSeek Base URL');
1249
+ }
1250
+ let cleanSecret;
1251
+ if (rawSecret !== '') {
1252
+ if (input.credentials === undefined) {
1253
+ return { ok: false, message: '凭证服务(credentials)未挂载,无法写入 DEEPSEEK_API_KEY' };
1254
+ }
1255
+ cleanSecret = validateApiKeyInput(rawSecret);
1256
+ }
1257
+ if (validatedUrl === undefined && cleanSecret === undefined) {
1258
+ return { ok: false, message: '未检测到改动(若只需保留现有密钥,请修改其他字段或填写新 API Key)' };
1259
+ }
1260
+ const updates = [];
1261
+ if (validatedUrl !== undefined && dsEntry !== undefined && input.settings !== undefined) {
1262
+ await input.settings.mutate(dsEntry.ns, [{ op: 'set', path: ['baseURL'], value: validatedUrl }], dsEntry.revision);
1263
+ updates.push('Base URL');
1264
+ }
1265
+ if (cleanSecret !== undefined && input.credentials !== undefined) {
1266
+ await input.credentials.set('DEEPSEEK_API_KEY', cleanSecret);
1267
+ updates.push('DEEPSEEK_API_KEY(已加密写入 0600 凭据库)');
1268
+ }
1269
+ return { ok: true, activeProviderId: 'deepseek-official', message: `deepseek-official 已更新:${updates.join('、')}` };
1270
+ }
1271
+ // llm-pi-ai provider create/update
1272
+ const piAiEntry = findSettingsEntry(descriptors, PI_AI_NAMESPACE_PATTERN);
1273
+ const providerIdRaw = selectedTarget === NEW_PROVIDER_SENTINEL || selectedTarget === ''
1274
+ ? (values['providerId'] ?? '').trim()
1275
+ : selectedTarget;
1276
+ if (!PROVIDER_ID_PATTERN.test(providerIdRaw) || RESERVED_PI_AI_PROVIDER_IDS.has(providerIdRaw)) {
1277
+ return { ok: false, message: `Provider ID 无效或不可用于自定义网关:${providerIdRaw || '(空)'}` };
1278
+ }
1279
+ const providersMap = asRecord(asRecord(piAiEntry?.value)['providers']);
1280
+ const existingProfile = asRecord(providersMap[providerIdRaw]);
1281
+ const isCreate = !Object.hasOwn(providersMap, providerIdRaw);
1282
+ const baseURLInput = values['baseURL']?.trim();
1283
+ const resolvedBaseURL = baseURLInput !== undefined && baseURLInput !== ''
1284
+ ? validateHttpUrl(baseURLInput, 'Base URL')
1285
+ : typeof existingProfile['baseURL'] === 'string' && existingProfile['baseURL'].trim() !== ''
1286
+ ? existingProfile['baseURL'].trim()
1287
+ : undefined;
1288
+ if (resolvedBaseURL === undefined) {
1289
+ return { ok: false, message: 'Base URL 为必填项,请填写 http:// 或 https:// 地址' };
1290
+ }
1291
+ const apiInput = values['api']?.trim();
1292
+ const resolvedApi = apiInput !== undefined && apiInput !== ''
1293
+ ? apiInput
1294
+ : typeof existingProfile['api'] === 'string'
1295
+ ? existingProfile['api']
1296
+ : 'openai-completions';
1297
+ if (!PI_AI_SUPPORTED_APIS.includes(resolvedApi)) {
1298
+ return { ok: false, message: `接口协议不受支持:${resolvedApi}` };
1299
+ }
1300
+ const modelsInput = values['models'];
1301
+ let resolvedModels;
1302
+ if (modelsInput !== undefined && modelsInput.trim() !== '') {
1303
+ const ids = [...new Set(modelsInput.split(/[,,\n\s]+/u).map(item => item.trim()).filter(Boolean))];
1304
+ if (ids.length === 0 || ids.length > 50 || ids.some(id => /[\p{Cc}]/u.test(id) || id.length > 256)) {
1305
+ return { ok: false, message: '模型 ID 列表无效,请使用逗号分隔合法模型 ID' };
1306
+ }
1307
+ const existingModels = Array.isArray(existingProfile['models']) ? existingProfile['models'] : [];
1308
+ resolvedModels = ids.map(id => {
1309
+ const match = existingModels.find(entry => asRecord(entry)['id'] === id);
1310
+ return match !== undefined && typeof match === 'object' ? { ...asRecord(match), id } : { id };
1311
+ });
1312
+ }
1313
+ else if (!isCreate && Array.isArray(existingProfile['models']) && existingProfile['models'].length > 0) {
1314
+ resolvedModels = existingProfile['models'];
1315
+ }
1316
+ else {
1317
+ return { ok: false, message: '请至少填写一个模型 ID(逗号分隔)' };
1318
+ }
1319
+ const displayNameInput = values['displayName']?.trim();
1320
+ const resolvedDisplayName = displayNameInput !== undefined && displayNameInput !== ''
1321
+ ? displayNameInput.slice(0, 120)
1322
+ : typeof existingProfile['displayName'] === 'string' && existingProfile['displayName'].trim() !== ''
1323
+ ? existingProfile['displayName'].trim()
1324
+ : providerIdRaw;
1325
+ const apiKeyEnvInput = values['apiKeyEnv']?.trim();
1326
+ const resolvedApiKeyEnv = validateCredentialRefName(apiKeyEnvInput !== undefined && apiKeyEnvInput !== ''
1327
+ ? apiKeyEnvInput
1328
+ : typeof existingProfile['apiKeyEnv'] === 'string' && CREDENTIAL_REF_PATTERN.test(existingProfile['apiKeyEnv'])
1329
+ ? existingProfile['apiKeyEnv']
1330
+ : deriveCredentialRefName(providerIdRaw));
1331
+ if (piAiEntry === undefined || input.settings === undefined) {
1332
+ return { ok: false, message: 'llm-pi-ai 或 Host settings 服务未挂载,无法保存 Provider' };
1333
+ }
1334
+ let cleanSecret;
1335
+ if (rawSecret !== '') {
1336
+ if (input.credentials === undefined) {
1337
+ return {
1338
+ ok: false,
1339
+ message: `凭证服务(credentials)未挂载,无法写入 ${resolvedApiKeyEnv};本次未保存 Provider ${providerIdRaw}`,
1340
+ };
1341
+ }
1342
+ cleanSecret = validateApiKeyInput(rawSecret);
1343
+ }
1344
+ const nextProfile = {
1345
+ ...existingProfile,
1346
+ displayName: resolvedDisplayName,
1347
+ api: resolvedApi,
1348
+ baseURL: resolvedBaseURL,
1349
+ apiKeyEnv: resolvedApiKeyEnv,
1350
+ models: resolvedModels,
1351
+ };
1352
+ await input.settings.mutate(piAiEntry.ns, [{ op: 'set', path: ['providers', providerIdRaw], value: nextProfile }], piAiEntry.revision);
1353
+ let keyNote = '(密钥未修改)';
1354
+ if (cleanSecret !== undefined && input.credentials !== undefined) {
1355
+ await input.credentials.set(resolvedApiKeyEnv, cleanSecret);
1356
+ keyNote = `(API Key 已安全写入 ${resolvedApiKeyEnv})`;
1357
+ }
1358
+ return {
1359
+ ok: true,
1360
+ activeProviderId: providerIdRaw,
1361
+ message: `${isCreate ? '已新增' : '已更新'} Provider ${providerIdRaw}${keyNote}`,
1362
+ };
1363
+ }
1364
+ catch (error) {
1365
+ const isConflict = typeof error === 'object' && error !== null
1366
+ && (error.code === 'SETTINGS_CONFLICT'
1367
+ || error.name === 'SettingsConflictError');
1368
+ const rawMessage = error instanceof Error ? error.message : String(error);
1369
+ const safeMessage = redactConfigSecret(rawMessage, input.ephemeralSecret);
1370
+ return {
1371
+ ok: false,
1372
+ ...(isConflict ? { conflict: true } : {}),
1373
+ message: isConflict
1374
+ ? '配置已被其他操作更新,已为您刷新最新状态,请确认后重试'
1375
+ : safeMessage,
1376
+ };
1377
+ }
1378
+ }
1379
+ export function formatConfigPickerPlainSummary(intent, notice) {
1380
+ const active = intent.categories.find(cat => cat.id === intent.activeCategory) ?? intent.categories[0];
1381
+ const lines = [
1382
+ `当前配置分类:${active?.label ?? intent.activeCategory}(${intent.conversationKind === 'dm' ? '私聊' : '群聊'})`,
1383
+ ...(notice === undefined ? [] : [`提示:${notice}`]),
1384
+ '',
1385
+ ];
1386
+ if (active !== undefined) {
1387
+ lines.push(active.subtitle);
1388
+ if (!active.available && active.unavailableReason !== undefined) {
1389
+ lines.push(`状态:不可用(${active.unavailableReason})`);
1390
+ }
1391
+ for (const field of active.fields) {
1392
+ if (field.kind === 'select') {
1393
+ lines.push(`- ${field.key}(${field.label}):${field.currentValue}`);
1394
+ }
1395
+ else {
1396
+ const display = field.inputType === 'password'
1397
+ ? (field.statusBadge ?? '已脱敏')
1398
+ : (field.currentValue ?? '');
1399
+ lines.push(`- ${field.key}(${field.label}):${display}`);
1400
+ }
1401
+ }
1402
+ }
1403
+ lines.push('', '可用命令:', '- /config conversation | lark | routing' + (intent.conversationKind === 'dm' ? ' | providers' : ''), '- /config <分类> set <键>=<值>');
1404
+ return lines.join('\n');
1405
+ }
1406
+ //# sourceMappingURL=config-control.js.map