dsh-total-quality 2.0.55 → 2.0.57

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 (197) hide show
  1. package/CONTRIBUTING.md +51 -47
  2. package/LICENSE.md +37 -37
  3. package/README.en.md +32 -30
  4. package/README.md +90 -88
  5. package/agent-host.cjs +277 -277
  6. package/client.js +199 -92
  7. package/cordis.patch.yml +5 -5
  8. package/docs/enterprise-onboarding.md +10 -10
  9. package/docs/technical-reference.md +223 -223
  10. package/host.cjs +91 -124
  11. package/llm-bridge.cjs +234 -234
  12. package/locale/en.json +5 -5
  13. package/locale/zh.json +5 -5
  14. package/package.json +3 -2
  15. package/public/app.css +3 -0
  16. package/public/app.js +6 -2
  17. package/public/index.html +8 -9
  18. package/public/js/api.js +152 -152
  19. package/public/js/assistant-history.js +62 -62
  20. package/public/js/material-library.js +100 -100
  21. package/public/js/mobile-preview.js +119 -0
  22. package/public/js/pages-company-knowledge.js +9 -32
  23. package/public/js/pages-core.js +232 -232
  24. package/public/js/pages-growth.js +148 -148
  25. package/public/js/pages-qms.js +1 -1
  26. package/public/js/pages-qtools.js +410 -410
  27. package/public/js/pages-thanks.js +71 -71
  28. package/public/js/plugin-updates.js +53 -0
  29. package/public/js/quality-workflow.js +205 -205
  30. package/public/js/survey-dates.js +41 -41
  31. package/public/js/survey-knowledge.js +301 -301
  32. package/public/js/tool-wizards.js +621 -621
  33. package/public/js/ui.js +467 -467
  34. package/public/js/voice-capture-worklet.js +30 -30
  35. package/public/js/xiaozhi-voice.js +264 -264
  36. package/public/js/xiaozhi.js +468 -468
  37. package/public/platform-help.html +426 -426
  38. package/public/platform-site/assets/0468a68574112812.css +10703 -10703
  39. package/public/platform-site/assets/159e086d35adfa1c.css +2094 -2094
  40. package/public/platform-site/assets/169e3159cade0d9f.css +98 -98
  41. package/public/platform-site/assets/22b917c4a3d4ae3d.svg +14 -14
  42. package/public/platform-site/assets/476f9254ccf723e7.css +8265 -8265
  43. package/public/platform-site/assets/85a0a4fb4416ded9.css +120 -120
  44. package/public/platform-site/assets/a3b272383226f6d9.svg +135 -135
  45. package/public/platform-site/assets/fd16dc5f3cc9d97e.svg +104 -104
  46. package/public/platform-site/assets/qip-favicon.svg +5 -5
  47. package/public/platform-site/index.html +279 -279
  48. package/public/platform-site/offline.js +261 -261
  49. package/public/platform-site/qip-brand.css +566 -566
  50. package/public/platform-site/qip-module-guides.js +237 -237
  51. package/public/responsive.css +103 -101
  52. package/public/vendor/markdown-it-15.0.3.LICENSE +22 -22
  53. package/public/vendor/markdown-it-15.0.3.umd.min.js +13 -13
  54. package/public/workbench.css +7 -7
  55. package/public/xiaozhi.css +292 -292
  56. package/resources/qms-templates/019ffb58f24ed48d.docx +0 -0
  57. package/resources/qms-templates/04a69165fc15143a.docx +0 -0
  58. package/resources/qms-templates/09af69358c989a63.docx +0 -0
  59. package/resources/qms-templates/0e7ac77844e45311.docx +0 -0
  60. package/resources/qms-templates/12446a1b5e173c71.docx +0 -0
  61. package/resources/qms-templates/15ae40f67f9a3efc.docx +0 -0
  62. package/resources/qms-templates/18a69bbebf2ece7f.docx +0 -0
  63. package/resources/qms-templates/1978faa989134f02.docx +0 -0
  64. package/resources/qms-templates/1a30e121de752f7b.docx +0 -0
  65. package/resources/qms-templates/1b88907969ea7d4c.docx +0 -0
  66. package/resources/qms-templates/1e92b808722bf90a.docx +0 -0
  67. package/resources/qms-templates/2091cad340dc0e7f.docx +0 -0
  68. package/resources/qms-templates/271ae1002c896ed7.docx +0 -0
  69. package/resources/qms-templates/280ce53e5d3b5fcf.docx +0 -0
  70. package/resources/qms-templates/28ca8e4ede0adf6d.docx +0 -0
  71. package/resources/qms-templates/2ac6675f3cb1f993.docx +0 -0
  72. package/resources/qms-templates/2c3b799389909d8b.docx +0 -0
  73. package/resources/qms-templates/2c51038ba2cc3264.docx +0 -0
  74. package/resources/qms-templates/30c888851d16d764.docx +0 -0
  75. package/resources/qms-templates/3459fc4daaa2743d.docx +0 -0
  76. package/resources/qms-templates/3751dafc335e0e80.docx +0 -0
  77. package/resources/qms-templates/38798cd4298cd2db.docx +0 -0
  78. package/resources/qms-templates/38f551f9d738ab0a.docx +0 -0
  79. package/resources/qms-templates/3c85a23ea17018b4.docx +0 -0
  80. package/resources/qms-templates/3cdb7d14caf1b852.docx +0 -0
  81. package/resources/qms-templates/3f23239bb6b3e1db.docx +0 -0
  82. package/resources/qms-templates/42a5b9efeeaa8007.docx +0 -0
  83. package/resources/qms-templates/47352aafe9b8dac1.docx +0 -0
  84. package/resources/qms-templates/495359b1e3cbb8fe.docx +0 -0
  85. package/resources/qms-templates/4ca6920464785166.docx +0 -0
  86. package/resources/qms-templates/4ce862582a7791be.docx +0 -0
  87. package/resources/qms-templates/54c9a02a10991b9e.docx +0 -0
  88. package/resources/qms-templates/5aeb8fddf5f3693f.docx +0 -0
  89. package/resources/qms-templates/5d7e5576b0e73be7.docx +0 -0
  90. package/resources/qms-templates/5db3a40edac37791.docx +0 -0
  91. package/resources/qms-templates/5ffa21eb78eb6f77.docx +0 -0
  92. package/resources/qms-templates/60d0fbcb709b7161.docx +0 -0
  93. package/resources/qms-templates/63e1d3a166756095.docx +0 -0
  94. package/resources/qms-templates/65c724c080d32f10.docx +0 -0
  95. package/resources/qms-templates/674bd7826c6cbac2.docx +0 -0
  96. package/resources/qms-templates/677e851acca1b879.docx +0 -0
  97. package/resources/qms-templates/6bf15feb1a0d2a8d.docx +0 -0
  98. package/resources/qms-templates/6c3889c7d0918db9.docx +0 -0
  99. package/resources/qms-templates/6c4c349eeb0a96a8.docx +0 -0
  100. package/resources/qms-templates/6c5befbd33f759c1.docx +0 -0
  101. package/resources/qms-templates/6df8367901347508.docx +0 -0
  102. package/resources/qms-templates/71db51997037692b.docx +0 -0
  103. package/resources/qms-templates/78a8ef8c76510c99.docx +0 -0
  104. package/resources/qms-templates/8397bfd1c0a1b013.docx +0 -0
  105. package/resources/qms-templates/84d750cf858b60a1.docx +0 -0
  106. package/resources/qms-templates/880de58a4b334533.docx +0 -0
  107. package/resources/qms-templates/88c37d1b87d9b78c.docx +0 -0
  108. package/resources/qms-templates/88e9cd42f1849462.docx +0 -0
  109. package/resources/qms-templates/8956597403be35b6.docx +0 -0
  110. package/resources/qms-templates/94675c810a233e1f.docx +0 -0
  111. package/resources/qms-templates/94dff59dd7ebec6e.docx +0 -0
  112. package/resources/qms-templates/9670b9cd02141594.docx +0 -0
  113. package/resources/qms-templates/98c373ebd7b5163d.docx +0 -0
  114. package/resources/qms-templates/a4078cf2378a9388.docx +0 -0
  115. package/resources/qms-templates/a5b110c7ef917139.docx +0 -0
  116. package/resources/qms-templates/aec75820e45774be.docx +0 -0
  117. package/resources/qms-templates/b31c085e281d230c.docx +0 -0
  118. package/resources/qms-templates/b7c1c3c72f8ffeef.docx +0 -0
  119. package/resources/qms-templates/b81b82eaa5c8f422.docx +0 -0
  120. package/resources/qms-templates/b92a2fa31f75f137.docx +0 -0
  121. package/resources/qms-templates/b96c54ae9cfffc54.docx +0 -0
  122. package/resources/qms-templates/bc47cfd626c010e7.docx +0 -0
  123. package/resources/qms-templates/be60792734afca69.docx +0 -0
  124. package/resources/qms-templates/c0018d8ae9ad19e1.docx +0 -0
  125. package/resources/qms-templates/c171027c964c8be3.docx +0 -0
  126. package/resources/qms-templates/c4b93d71f5d98b4b.docx +0 -0
  127. package/resources/qms-templates/c531da29fcb3090f.docx +0 -0
  128. package/resources/qms-templates/c88eddd43358d015.docx +0 -0
  129. package/resources/qms-templates/cb978da542f0d892.docx +0 -0
  130. package/resources/qms-templates/ccde4a94532a8d36.docx +0 -0
  131. package/resources/qms-templates/cf3fb1e20ae6f24d.docx +0 -0
  132. package/resources/qms-templates/d231b4982fc8113e.docx +0 -0
  133. package/resources/qms-templates/d3c55aa5ed14055c.docx +0 -0
  134. package/resources/qms-templates/db45c44a00a13349.docx +0 -0
  135. package/resources/qms-templates/db849a41210f54e0.docx +0 -0
  136. package/resources/qms-templates/dba9ce363d83ddc8.docx +0 -0
  137. package/resources/qms-templates/dca3ea4c95eb2225.docx +0 -0
  138. package/resources/qms-templates/dfa4220d2b6b8131.docx +0 -0
  139. package/resources/qms-templates/dfa51222c777734f.docx +0 -0
  140. package/resources/qms-templates/e07ea511507e14f5.docx +0 -0
  141. package/resources/qms-templates/e0a2e00c03458dfa.docx +0 -0
  142. package/resources/qms-templates/e0e802f46b6764d1.docx +0 -0
  143. package/resources/qms-templates/e53fc85717f2852b.docx +0 -0
  144. package/resources/qms-templates/e9dd82d5e54520e5.docx +0 -0
  145. package/resources/qms-templates/ea7bfc22c06d82a9.docx +0 -0
  146. package/resources/qms-templates/ecf0db9f37294536.docx +0 -0
  147. package/resources/qms-templates/f05fcfc87e82ff39.docx +0 -0
  148. package/resources/qms-templates/fb9e56a17c4a4f97.docx +0 -0
  149. package/resources/qms-templates/manifest.json +932 -0
  150. package/src/data/seed-sme.js +317 -317
  151. package/src/data/seed.js +879 -879
  152. package/src/lib/backup-identity.js +57 -57
  153. package/src/lib/chat-answer.js +225 -225
  154. package/src/lib/chat-context.js +99 -99
  155. package/src/lib/company-library.js +28 -19
  156. package/src/lib/data-import.js +217 -217
  157. package/src/lib/data-sources.js +118 -118
  158. package/src/lib/demo-data.js +27 -1
  159. package/src/lib/employee-intake.js +84 -84
  160. package/src/lib/growth.js +53 -53
  161. package/src/lib/intake-packets.js +119 -119
  162. package/src/lib/issue-intake.js +88 -88
  163. package/src/lib/kb-revision.js +214 -214
  164. package/src/lib/llm.js +279 -279
  165. package/src/lib/model-error.js +14 -14
  166. package/src/lib/privacy.js +26 -26
  167. package/src/lib/qms-drafting.js +194 -194
  168. package/src/lib/qms-jobs.js +11 -7
  169. package/src/lib/qms-manual-review.js +185 -185
  170. package/src/lib/qms-procedure-review.js +109 -109
  171. package/src/lib/qms-templates.js +358 -326
  172. package/src/lib/qms.js +369 -369
  173. package/src/lib/quality-priority.js +100 -100
  174. package/src/lib/quality-state.js +92 -92
  175. package/src/lib/quality-workflow.js +65 -65
  176. package/src/lib/retrieval.js +159 -159
  177. package/src/lib/spc.js +127 -127
  178. package/src/lib/voice-hotwords.txt +22 -22
  179. package/src/lib/voice-text.js +13 -13
  180. package/src/lib/voice-worker.js +72 -72
  181. package/src/lib/voice.js +330 -330
  182. package/src/lib/workbench-notices.js +49 -49
  183. package/src/lib/workbench.js +103 -106
  184. package/src/package.json +3 -3
  185. package/src/tools/analysis.js +306 -306
  186. package/src/tools/data.js +596 -596
  187. package/src/tools/docs.js +430 -430
  188. package/src/tools/registry.js +57 -57
  189. package/tools-dsh.cjs +153 -153
  190. package//345/256/211/350/243/205/350/257/264/346/230/216.md +33 -25
  191. package//346/234/254/346/234/272/347/213/254/347/253/213/345/256/211/350/243/205/350/257/264/346/230/216.md +17 -17
  192. package//350/207/252/346/243/200.cjs +88 -88
  193. package/public/js/remote-knowledge.js +0 -165
  194. package/public/js/workbench-notices.js +0 -67
  195. package/public/remote-knowledge-help.html +0 -35
  196. package/public/remote-knowledge.css +0 -40
  197. package/src/lib/remote-knowledge.js +0 -284
package/src/lib/llm.js CHANGED
@@ -1,279 +1,279 @@
1
- 'use strict';
2
- /**
3
- * LLM 客户端(零依赖,Node 18+ 内置 fetch)
4
- * ------------------------------------------------------------------
5
- * 兼容任何 OpenAI 风格的 /chat/completions 端点:
6
- * · DeepSeek 官方 baseUrl = https://api.deepseek.com
7
- * · 厂内私有化部署 baseUrl = http://10.x.x.x:8000/v1 (vLLM / TGI / Ollama OpenAI 兼容层)
8
- * · 其它兼容网关 baseUrl = https://xxx/v1
9
- * 支持:流式 SSE、工具调用(function calling)增量拼装、reasoning_content 思维链、
10
- * 超时控制、错误归一化、用量统计。
11
- */
12
- const DEFAULT_TIMEOUT = 120000;
13
-
14
- function normalizeBase(baseUrl) {
15
- let b = String(baseUrl || '').trim().replace(/\/+$/, '');
16
- if (!b) b = 'https://api.deepseek.com';
17
- // Ollama 原生端口给出提示式兼容
18
- if (/\/v1$/.test(b)) return b;
19
- if (/ollama/i.test(b) && !/\/v1/.test(b)) return b + '/v1';
20
- return b;
21
- }
22
-
23
- function buildUrl(baseUrl, path) {
24
- const b = normalizeBase(baseUrl);
25
- // DeepSeek 官方同时支持 /chat/completions 与 /v1/chat/completions
26
- const p = path.replace(/^\//, '');
27
- return b + '/' + p;
28
- }
29
-
30
- class LLMError extends Error {
31
- constructor(message, status, body) {
32
- super(message);
33
- this.name = 'LLMError';
34
- this.status = status;
35
- this.body = body;
36
- }
37
- }
38
-
39
- /**
40
- * 发起一次 chat completion
41
- * @param {object} cfg {baseUrl, apiKey, model, temperature, maxTokens, timeoutMs}
42
- * @param {Array} messages OpenAI 格式消息
43
- * @param {object} opts {tools, toolChoice, stream, onDelta, signal, jsonMode}
44
- * @returns {Promise<{content:string, reasoning:string, toolCalls:Array, usage:object, finishReason:string, raw:object}>}
45
- */
46
- async function chat(cfg, messages, opts = {}) {
47
- const baseUrl = normalizeBase(cfg.baseUrl);
48
- const model = cfg.model || 'deepseek-chat';
49
- const body = {
50
- model,
51
- messages,
52
- temperature: cfg.temperature === undefined ? 0.3 : cfg.temperature,
53
- stream: !!opts.stream,
54
- };
55
- if (cfg.maxTokens) body.max_tokens = cfg.maxTokens;
56
- if (opts.tools && opts.tools.length) {
57
- body.tools = opts.tools;
58
- body.tool_choice = opts.toolChoice || 'auto';
59
- }
60
- if (opts.jsonMode) body.response_format = { type: 'json_object' };
61
-
62
- const ctrl = new AbortController();
63
- const timeout = cfg.timeoutMs || DEFAULT_TIMEOUT;
64
- const timer = setTimeout(() => ctrl.abort(new Error('LLM 请求超时(' + Math.round(timeout / 1000) + 's)')), timeout);
65
- if (opts.signal) {
66
- if (opts.signal.aborted) ctrl.abort();
67
- else opts.signal.addEventListener('abort', () => ctrl.abort(), { once: true });
68
- }
69
-
70
- const headers = { 'Content-Type': 'application/json' };
71
- if (cfg.apiKey) headers['Authorization'] = 'Bearer ' + cfg.apiKey;
72
- if (cfg.extraHeaders) Object.assign(headers, cfg.extraHeaders);
73
-
74
- let res;
75
- try {
76
- res = await fetch(buildUrl(baseUrl, 'chat/completions'), {
77
- method: 'POST',
78
- headers,
79
- body: JSON.stringify(body),
80
- signal: ctrl.signal,
81
- });
82
- } catch (e) {
83
- clearTimeout(timer);
84
- const msg = e && e.name === 'AbortError' ? 'LLM 请求已中止或超时:' + (ctrl.signal.reason && ctrl.signal.reason.message ? ctrl.signal.reason.message : e.message) : 'LLM 网络请求失败:' + (e && e.message);
85
- throw new LLMError(msg, 0, null);
86
- }
87
-
88
- if (!res.ok) {
89
- clearTimeout(timer);
90
- let text = '';
91
- try { text = await res.text(); } catch (_) {}
92
- throw new LLMError(explainHttpError(res.status, text, baseUrl), res.status, text);
93
- }
94
-
95
- if (!body.stream) {
96
- clearTimeout(timer);
97
- const json = await res.json();
98
- const choice = (json.choices && json.choices[0]) || {};
99
- const msg = choice.message || {};
100
- const out = {
101
- content: msg.content || '',
102
- reasoning: msg.reasoning_content || msg.reasoning || '',
103
- toolCalls: (msg.tool_calls || []).map(normalizeToolCall),
104
- usage: json.usage || {},
105
- finishReason: choice.finish_reason || 'stop',
106
- raw: json,
107
- };
108
- if (opts.onDelta) {
109
- if (out.reasoning) opts.onDelta({ type: 'reasoning', text: out.reasoning });
110
- if (out.content) opts.onDelta({ type: 'content', text: out.content });
111
- }
112
- return out;
113
- }
114
-
115
- // ---------------- 流式解析 ----------------
116
- const acc = { content: '', reasoning: '', toolCalls: [], usage: {}, finishReason: 'stop' };
117
- const reader = res.body.getReader();
118
- const decoder = new TextDecoder('utf-8');
119
- let buf = '';
120
- /** 流式 tool_calls 按 index 拼装 */
121
- const toolMap = new Map();
122
-
123
- function handleChunk(json) {
124
- if (json.usage) acc.usage = json.usage;
125
- const choice = (json.choices && json.choices[0]) || {};
126
- if (choice.finish_reason) acc.finishReason = choice.finish_reason;
127
- const delta = choice.delta || {};
128
- if (delta.reasoning_content) {
129
- acc.reasoning += delta.reasoning_content;
130
- if (opts.onDelta) opts.onDelta({ type: 'reasoning', text: delta.reasoning_content });
131
- }
132
- if (delta.content) {
133
- acc.content += delta.content;
134
- if (opts.onDelta) opts.onDelta({ type: 'content', text: delta.content });
135
- }
136
- if (delta.tool_calls) {
137
- for (const tc of delta.tool_calls) {
138
- const idx = tc.index === undefined ? 0 : tc.index;
139
- if (!toolMap.has(idx)) toolMap.set(idx, { id: '', type: 'function', function: { name: '', arguments: '' } });
140
- const cur = toolMap.get(idx);
141
- if (tc.id) cur.id = tc.id;
142
- if (tc.type) cur.type = tc.type;
143
- if (tc.function) {
144
- if (tc.function.name) cur.function.name += tc.function.name;
145
- if (tc.function.arguments) cur.function.arguments += tc.function.arguments;
146
- }
147
- if (opts.onDelta) opts.onDelta({ type: 'tool_call_delta', index: idx, name: tc.function && tc.function.name, args: tc.function && tc.function.arguments });
148
- }
149
- }
150
- }
151
-
152
- try {
153
- for (;;) {
154
- const { done, value } = await reader.read();
155
- if (done) break;
156
- buf += decoder.decode(value, { stream: true });
157
- let nl;
158
- while ((nl = buf.indexOf('\n')) >= 0) {
159
- let line = buf.slice(0, nl);
160
- buf = buf.slice(nl + 1);
161
- line = line.replace(/\r$/, '');
162
- if (!line) continue;
163
- if (line.startsWith(':')) continue; // SSE 注释/心跳
164
- if (!line.startsWith('data:')) continue;
165
- const data = line.slice(5).trim();
166
- if (data === '[DONE]') { buf = ''; break; }
167
- try { handleChunk(JSON.parse(data)); } catch (_) { /* 忽略不完整分片 */ }
168
- }
169
- }
170
- } catch (e) {
171
- clearTimeout(timer);
172
- throw new LLMError('LLM 流式读取中断:' + (e && e.message), 0, null);
173
- }
174
- clearTimeout(timer);
175
-
176
- acc.toolCalls = [...toolMap.keys()].sort((a, b) => a - b).map((k) => normalizeToolCall(toolMap.get(k)));
177
- return acc;
178
- }
179
-
180
- function normalizeToolCall(tc) {
181
- const fn = tc.function || {};
182
- let args = fn.arguments;
183
- if (typeof args === 'string') {
184
- const s = args.trim();
185
- if (!s) args = {};
186
- else { try { args = JSON.parse(s); } catch (_) { args = { __raw: s, __parseError: true }; } }
187
- }
188
- return {
189
- id: tc.id || 'call_' + Math.random().toString(36).slice(2, 10),
190
- type: 'function',
191
- name: fn.name || '',
192
- arguments: args || {},
193
- rawArguments: typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {}),
194
- };
195
- }
196
-
197
- /** 把 HTTP 错误翻译成运维一眼能懂的提示 */
198
- function explainHttpError(status, text, baseUrl) {
199
- let detail = text || '';
200
- try { const j = JSON.parse(text); detail = (j.error && (j.error.message || j.error.code)) || j.message || text; } catch (_) {}
201
- const tips = {
202
- 401: 'API Key 无效或已过期,请在「系统设置 → 模型接入」中重新填写。',
203
- 402: '账户余额不足(DeepSeek 按量计费),请先充值。',
204
- 403: '无权限访问该模型或该接口。',
205
- 404: '接口地址不存在。请检查 Base URL(DeepSeek 官方为 https://api.deepseek.com,自建服务通常需要在末尾加 /v1)。',
206
- 422: '请求参数不合法(常见原因:模型名写错、消息格式不合法)。',
207
- 429: '请求过于频繁或超出配额,请稍后重试。',
208
- 500: '模型服务端错误,请稍后重试。',
209
- 502: '网关错误:上游模型服务不可达(自建部署请确认 vLLM/Ollama 已启动)。',
210
- 503: '模型服务暂不可用(自建部署常见:服务未启动或显存不足)。',
211
- 504: '网关超时。',
212
- };
213
- return '模型接口返回 ' + status + ':' + (tips[status] || '未知错误。') + (detail ? ' 服务端信息:' + String(detail).slice(0, 400) : '') + '(当前 Base URL:' + normalizeBase(baseUrl) + ')';
214
- }
215
-
216
- /**
217
- * 连通性自检:依次尝试 models 列表与一次极短对话
218
- * @returns {Promise<{ok:boolean, steps:Array<{name:string, ok:boolean, detail:string, ms:number}>}>}
219
- */
220
- async function testConnection(cfg) {
221
- const steps = [];
222
- // 1) /models
223
- let t0 = Date.now();
224
- try {
225
- const headers = {};
226
- if (cfg.apiKey) headers['Authorization'] = 'Bearer ' + cfg.apiKey;
227
- const res = await fetch(buildUrl(cfg.baseUrl, 'models'), { headers, signal: AbortSignal.timeout(15000) });
228
- const ms = Date.now() - t0;
229
- if (res.ok) {
230
- const j = await res.json().catch(() => ({}));
231
- const ids = (j.data || []).map((m) => m.id).slice(0, 20);
232
- steps.push({ name: '① 接口连通性(GET /models)', ok: true, detail: '可达;可用模型:' + (ids.join(', ') || '未返回列表'), ms });
233
- } else {
234
- const txt = await res.text().catch(() => '');
235
- steps.push({ name: '① 接口连通性(GET /models)', ok: false, detail: explainHttpError(res.status, txt, cfg.baseUrl), ms });
236
- }
237
- } catch (e) {
238
- steps.push({ name: '① 接口连通性(GET /models)', ok: false, detail: '无法连接:' + e.message, ms: Date.now() - t0 });
239
- }
240
- // 2) 最小对话
241
- t0 = Date.now();
242
- try {
243
- const r = await chat(Object.assign({}, cfg, { maxTokens: 32, timeoutMs: 30000 }), [
244
- { role: 'user', content: '请只回复两个字:正常' },
245
- ], { stream: false, tools: [] });
246
- steps.push({ name: '② 对话推理(POST /chat/completions)', ok: true, detail: '模型 ' + (cfg.model || 'deepseek-chat') + ' 回复:' + (r.content || '').trim().slice(0, 40), ms: Date.now() - t0 });
247
- } catch (e) {
248
- steps.push({ name: '② 对话推理(POST /chat/completions)', ok: false, detail: e.message, ms: Date.now() - t0 });
249
- }
250
- // 3) 工具调用能力
251
- t0 = Date.now();
252
- try {
253
- const r = await chat(Object.assign({}, cfg, { maxTokens: 128, timeoutMs: 45000 }), [
254
- { role: 'user', content: '请调用工具 get_now 查询当前时间。' },
255
- ], {
256
- stream: false,
257
- tools: [{ type: 'function', function: { name: 'get_now', description: '获取当前时间', parameters: { type: 'object', properties: {}, required: [] } } }],
258
- });
259
- const ok = r.toolCalls && r.toolCalls.length > 0;
260
- steps.push({ name: '③ 工具调用能力(function calling)', ok, detail: ok ? '模型正确发起工具调用:' + r.toolCalls[0].name : '模型未发起工具调用(该模型可能不支持 function calling,智能体将无法自动查数)', ms: Date.now() - t0 });
261
- } catch (e) {
262
- steps.push({ name: '③ 工具调用能力(function calling)', ok: false, detail: e.message, ms: Date.now() - t0 });
263
- }
264
- // 4) 流式能力
265
- t0 = Date.now();
266
- try {
267
- let got = 0;
268
- await chat(Object.assign({}, cfg, { maxTokens: 32, timeoutMs: 30000 }), [{ role: 'user', content: '数到三' }], {
269
- stream: true, tools: [], onDelta: (d) => { if (d.type === 'content') got += d.text.length; },
270
- });
271
- steps.push({ name: '④ 流式输出(SSE)', ok: got > 0, detail: got > 0 ? '流式正常,收到 ' + got + ' 个字符' : '未收到流式内容', ms: Date.now() - t0 });
272
- } catch (e) {
273
- steps.push({ name: '④ 流式输出(SSE)', ok: false, detail: e.message, ms: Date.now() - t0 });
274
- }
275
-
276
- return { ok: steps.every((s) => s.ok), steps };
277
- }
278
-
279
- module.exports = { chat, testConnection, LLMError, normalizeBase };
1
+ 'use strict';
2
+ /**
3
+ * LLM 客户端(零依赖,Node 18+ 内置 fetch)
4
+ * ------------------------------------------------------------------
5
+ * 兼容任何 OpenAI 风格的 /chat/completions 端点:
6
+ * · DeepSeek 官方 baseUrl = https://api.deepseek.com
7
+ * · 厂内私有化部署 baseUrl = http://10.x.x.x:8000/v1 (vLLM / TGI / Ollama OpenAI 兼容层)
8
+ * · 其它兼容网关 baseUrl = https://xxx/v1
9
+ * 支持:流式 SSE、工具调用(function calling)增量拼装、reasoning_content 思维链、
10
+ * 超时控制、错误归一化、用量统计。
11
+ */
12
+ const DEFAULT_TIMEOUT = 120000;
13
+
14
+ function normalizeBase(baseUrl) {
15
+ let b = String(baseUrl || '').trim().replace(/\/+$/, '');
16
+ if (!b) b = 'https://api.deepseek.com';
17
+ // Ollama 原生端口给出提示式兼容
18
+ if (/\/v1$/.test(b)) return b;
19
+ if (/ollama/i.test(b) && !/\/v1/.test(b)) return b + '/v1';
20
+ return b;
21
+ }
22
+
23
+ function buildUrl(baseUrl, path) {
24
+ const b = normalizeBase(baseUrl);
25
+ // DeepSeek 官方同时支持 /chat/completions 与 /v1/chat/completions
26
+ const p = path.replace(/^\//, '');
27
+ return b + '/' + p;
28
+ }
29
+
30
+ class LLMError extends Error {
31
+ constructor(message, status, body) {
32
+ super(message);
33
+ this.name = 'LLMError';
34
+ this.status = status;
35
+ this.body = body;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 发起一次 chat completion
41
+ * @param {object} cfg {baseUrl, apiKey, model, temperature, maxTokens, timeoutMs}
42
+ * @param {Array} messages OpenAI 格式消息
43
+ * @param {object} opts {tools, toolChoice, stream, onDelta, signal, jsonMode}
44
+ * @returns {Promise<{content:string, reasoning:string, toolCalls:Array, usage:object, finishReason:string, raw:object}>}
45
+ */
46
+ async function chat(cfg, messages, opts = {}) {
47
+ const baseUrl = normalizeBase(cfg.baseUrl);
48
+ const model = cfg.model || 'deepseek-chat';
49
+ const body = {
50
+ model,
51
+ messages,
52
+ temperature: cfg.temperature === undefined ? 0.3 : cfg.temperature,
53
+ stream: !!opts.stream,
54
+ };
55
+ if (cfg.maxTokens) body.max_tokens = cfg.maxTokens;
56
+ if (opts.tools && opts.tools.length) {
57
+ body.tools = opts.tools;
58
+ body.tool_choice = opts.toolChoice || 'auto';
59
+ }
60
+ if (opts.jsonMode) body.response_format = { type: 'json_object' };
61
+
62
+ const ctrl = new AbortController();
63
+ const timeout = cfg.timeoutMs || DEFAULT_TIMEOUT;
64
+ const timer = setTimeout(() => ctrl.abort(new Error('LLM 请求超时(' + Math.round(timeout / 1000) + 's)')), timeout);
65
+ if (opts.signal) {
66
+ if (opts.signal.aborted) ctrl.abort();
67
+ else opts.signal.addEventListener('abort', () => ctrl.abort(), { once: true });
68
+ }
69
+
70
+ const headers = { 'Content-Type': 'application/json' };
71
+ if (cfg.apiKey) headers['Authorization'] = 'Bearer ' + cfg.apiKey;
72
+ if (cfg.extraHeaders) Object.assign(headers, cfg.extraHeaders);
73
+
74
+ let res;
75
+ try {
76
+ res = await fetch(buildUrl(baseUrl, 'chat/completions'), {
77
+ method: 'POST',
78
+ headers,
79
+ body: JSON.stringify(body),
80
+ signal: ctrl.signal,
81
+ });
82
+ } catch (e) {
83
+ clearTimeout(timer);
84
+ const msg = e && e.name === 'AbortError' ? 'LLM 请求已中止或超时:' + (ctrl.signal.reason && ctrl.signal.reason.message ? ctrl.signal.reason.message : e.message) : 'LLM 网络请求失败:' + (e && e.message);
85
+ throw new LLMError(msg, 0, null);
86
+ }
87
+
88
+ if (!res.ok) {
89
+ clearTimeout(timer);
90
+ let text = '';
91
+ try { text = await res.text(); } catch (_) {}
92
+ throw new LLMError(explainHttpError(res.status, text, baseUrl), res.status, text);
93
+ }
94
+
95
+ if (!body.stream) {
96
+ clearTimeout(timer);
97
+ const json = await res.json();
98
+ const choice = (json.choices && json.choices[0]) || {};
99
+ const msg = choice.message || {};
100
+ const out = {
101
+ content: msg.content || '',
102
+ reasoning: msg.reasoning_content || msg.reasoning || '',
103
+ toolCalls: (msg.tool_calls || []).map(normalizeToolCall),
104
+ usage: json.usage || {},
105
+ finishReason: choice.finish_reason || 'stop',
106
+ raw: json,
107
+ };
108
+ if (opts.onDelta) {
109
+ if (out.reasoning) opts.onDelta({ type: 'reasoning', text: out.reasoning });
110
+ if (out.content) opts.onDelta({ type: 'content', text: out.content });
111
+ }
112
+ return out;
113
+ }
114
+
115
+ // ---------------- 流式解析 ----------------
116
+ const acc = { content: '', reasoning: '', toolCalls: [], usage: {}, finishReason: 'stop' };
117
+ const reader = res.body.getReader();
118
+ const decoder = new TextDecoder('utf-8');
119
+ let buf = '';
120
+ /** 流式 tool_calls 按 index 拼装 */
121
+ const toolMap = new Map();
122
+
123
+ function handleChunk(json) {
124
+ if (json.usage) acc.usage = json.usage;
125
+ const choice = (json.choices && json.choices[0]) || {};
126
+ if (choice.finish_reason) acc.finishReason = choice.finish_reason;
127
+ const delta = choice.delta || {};
128
+ if (delta.reasoning_content) {
129
+ acc.reasoning += delta.reasoning_content;
130
+ if (opts.onDelta) opts.onDelta({ type: 'reasoning', text: delta.reasoning_content });
131
+ }
132
+ if (delta.content) {
133
+ acc.content += delta.content;
134
+ if (opts.onDelta) opts.onDelta({ type: 'content', text: delta.content });
135
+ }
136
+ if (delta.tool_calls) {
137
+ for (const tc of delta.tool_calls) {
138
+ const idx = tc.index === undefined ? 0 : tc.index;
139
+ if (!toolMap.has(idx)) toolMap.set(idx, { id: '', type: 'function', function: { name: '', arguments: '' } });
140
+ const cur = toolMap.get(idx);
141
+ if (tc.id) cur.id = tc.id;
142
+ if (tc.type) cur.type = tc.type;
143
+ if (tc.function) {
144
+ if (tc.function.name) cur.function.name += tc.function.name;
145
+ if (tc.function.arguments) cur.function.arguments += tc.function.arguments;
146
+ }
147
+ if (opts.onDelta) opts.onDelta({ type: 'tool_call_delta', index: idx, name: tc.function && tc.function.name, args: tc.function && tc.function.arguments });
148
+ }
149
+ }
150
+ }
151
+
152
+ try {
153
+ for (;;) {
154
+ const { done, value } = await reader.read();
155
+ if (done) break;
156
+ buf += decoder.decode(value, { stream: true });
157
+ let nl;
158
+ while ((nl = buf.indexOf('\n')) >= 0) {
159
+ let line = buf.slice(0, nl);
160
+ buf = buf.slice(nl + 1);
161
+ line = line.replace(/\r$/, '');
162
+ if (!line) continue;
163
+ if (line.startsWith(':')) continue; // SSE 注释/心跳
164
+ if (!line.startsWith('data:')) continue;
165
+ const data = line.slice(5).trim();
166
+ if (data === '[DONE]') { buf = ''; break; }
167
+ try { handleChunk(JSON.parse(data)); } catch (_) { /* 忽略不完整分片 */ }
168
+ }
169
+ }
170
+ } catch (e) {
171
+ clearTimeout(timer);
172
+ throw new LLMError('LLM 流式读取中断:' + (e && e.message), 0, null);
173
+ }
174
+ clearTimeout(timer);
175
+
176
+ acc.toolCalls = [...toolMap.keys()].sort((a, b) => a - b).map((k) => normalizeToolCall(toolMap.get(k)));
177
+ return acc;
178
+ }
179
+
180
+ function normalizeToolCall(tc) {
181
+ const fn = tc.function || {};
182
+ let args = fn.arguments;
183
+ if (typeof args === 'string') {
184
+ const s = args.trim();
185
+ if (!s) args = {};
186
+ else { try { args = JSON.parse(s); } catch (_) { args = { __raw: s, __parseError: true }; } }
187
+ }
188
+ return {
189
+ id: tc.id || 'call_' + Math.random().toString(36).slice(2, 10),
190
+ type: 'function',
191
+ name: fn.name || '',
192
+ arguments: args || {},
193
+ rawArguments: typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {}),
194
+ };
195
+ }
196
+
197
+ /** 把 HTTP 错误翻译成运维一眼能懂的提示 */
198
+ function explainHttpError(status, text, baseUrl) {
199
+ let detail = text || '';
200
+ try { const j = JSON.parse(text); detail = (j.error && (j.error.message || j.error.code)) || j.message || text; } catch (_) {}
201
+ const tips = {
202
+ 401: 'API Key 无效或已过期,请在「系统设置 → 模型接入」中重新填写。',
203
+ 402: '账户余额不足(DeepSeek 按量计费),请先充值。',
204
+ 403: '无权限访问该模型或该接口。',
205
+ 404: '接口地址不存在。请检查 Base URL(DeepSeek 官方为 https://api.deepseek.com,自建服务通常需要在末尾加 /v1)。',
206
+ 422: '请求参数不合法(常见原因:模型名写错、消息格式不合法)。',
207
+ 429: '请求过于频繁或超出配额,请稍后重试。',
208
+ 500: '模型服务端错误,请稍后重试。',
209
+ 502: '网关错误:上游模型服务不可达(自建部署请确认 vLLM/Ollama 已启动)。',
210
+ 503: '模型服务暂不可用(自建部署常见:服务未启动或显存不足)。',
211
+ 504: '网关超时。',
212
+ };
213
+ return '模型接口返回 ' + status + ':' + (tips[status] || '未知错误。') + (detail ? ' 服务端信息:' + String(detail).slice(0, 400) : '') + '(当前 Base URL:' + normalizeBase(baseUrl) + ')';
214
+ }
215
+
216
+ /**
217
+ * 连通性自检:依次尝试 models 列表与一次极短对话
218
+ * @returns {Promise<{ok:boolean, steps:Array<{name:string, ok:boolean, detail:string, ms:number}>}>}
219
+ */
220
+ async function testConnection(cfg) {
221
+ const steps = [];
222
+ // 1) /models
223
+ let t0 = Date.now();
224
+ try {
225
+ const headers = {};
226
+ if (cfg.apiKey) headers['Authorization'] = 'Bearer ' + cfg.apiKey;
227
+ const res = await fetch(buildUrl(cfg.baseUrl, 'models'), { headers, signal: AbortSignal.timeout(15000) });
228
+ const ms = Date.now() - t0;
229
+ if (res.ok) {
230
+ const j = await res.json().catch(() => ({}));
231
+ const ids = (j.data || []).map((m) => m.id).slice(0, 20);
232
+ steps.push({ name: '① 接口连通性(GET /models)', ok: true, detail: '可达;可用模型:' + (ids.join(', ') || '未返回列表'), ms });
233
+ } else {
234
+ const txt = await res.text().catch(() => '');
235
+ steps.push({ name: '① 接口连通性(GET /models)', ok: false, detail: explainHttpError(res.status, txt, cfg.baseUrl), ms });
236
+ }
237
+ } catch (e) {
238
+ steps.push({ name: '① 接口连通性(GET /models)', ok: false, detail: '无法连接:' + e.message, ms: Date.now() - t0 });
239
+ }
240
+ // 2) 最小对话
241
+ t0 = Date.now();
242
+ try {
243
+ const r = await chat(Object.assign({}, cfg, { maxTokens: 32, timeoutMs: 30000 }), [
244
+ { role: 'user', content: '请只回复两个字:正常' },
245
+ ], { stream: false, tools: [] });
246
+ steps.push({ name: '② 对话推理(POST /chat/completions)', ok: true, detail: '模型 ' + (cfg.model || 'deepseek-chat') + ' 回复:' + (r.content || '').trim().slice(0, 40), ms: Date.now() - t0 });
247
+ } catch (e) {
248
+ steps.push({ name: '② 对话推理(POST /chat/completions)', ok: false, detail: e.message, ms: Date.now() - t0 });
249
+ }
250
+ // 3) 工具调用能力
251
+ t0 = Date.now();
252
+ try {
253
+ const r = await chat(Object.assign({}, cfg, { maxTokens: 128, timeoutMs: 45000 }), [
254
+ { role: 'user', content: '请调用工具 get_now 查询当前时间。' },
255
+ ], {
256
+ stream: false,
257
+ tools: [{ type: 'function', function: { name: 'get_now', description: '获取当前时间', parameters: { type: 'object', properties: {}, required: [] } } }],
258
+ });
259
+ const ok = r.toolCalls && r.toolCalls.length > 0;
260
+ steps.push({ name: '③ 工具调用能力(function calling)', ok, detail: ok ? '模型正确发起工具调用:' + r.toolCalls[0].name : '模型未发起工具调用(该模型可能不支持 function calling,智能体将无法自动查数)', ms: Date.now() - t0 });
261
+ } catch (e) {
262
+ steps.push({ name: '③ 工具调用能力(function calling)', ok: false, detail: e.message, ms: Date.now() - t0 });
263
+ }
264
+ // 4) 流式能力
265
+ t0 = Date.now();
266
+ try {
267
+ let got = 0;
268
+ await chat(Object.assign({}, cfg, { maxTokens: 32, timeoutMs: 30000 }), [{ role: 'user', content: '数到三' }], {
269
+ stream: true, tools: [], onDelta: (d) => { if (d.type === 'content') got += d.text.length; },
270
+ });
271
+ steps.push({ name: '④ 流式输出(SSE)', ok: got > 0, detail: got > 0 ? '流式正常,收到 ' + got + ' 个字符' : '未收到流式内容', ms: Date.now() - t0 });
272
+ } catch (e) {
273
+ steps.push({ name: '④ 流式输出(SSE)', ok: false, detail: e.message, ms: Date.now() - t0 });
274
+ }
275
+
276
+ return { ok: steps.every((s) => s.ok), steps };
277
+ }
278
+
279
+ module.exports = { chat, testConnection, LLMError, normalizeBase };
@@ -1,14 +1,14 @@
1
- 'use strict';
2
-
3
- function modelProblem(error) {
4
- const message = String(error?.message || '');
5
- if (/insufficient (?:balance|quota)|余额不足|额度不足/i.test(message)) {
6
- return { reason:'model-balance', message:'DeepSeek 调用额度不足。恢复额度或接入可用模型后可重试。' };
7
- }
8
- if (error?.code==='NO_MODEL' || /no API key|missing API key|not authenticated/i.test(message)) {
9
- return { reason:'model-credentials', message:'DSH 当前没有可用的模型接入。请在 DSH 模型设置中检查接入状态。' };
10
- }
11
- return null;
12
- }
13
-
14
- module.exports = { modelProblem };
1
+ 'use strict';
2
+
3
+ function modelProblem(error) {
4
+ const message = String(error?.message || '');
5
+ if (/insufficient (?:balance|quota)|余额不足|额度不足/i.test(message)) {
6
+ return { reason:'model-balance', message:'DeepSeek 调用额度不足。恢复额度或接入可用模型后可重试。' };
7
+ }
8
+ if (error?.code==='NO_MODEL' || /no API key|missing API key|not authenticated/i.test(message)) {
9
+ return { reason:'model-credentials', message:'DSH 当前没有可用的模型接入。请在 DSH 模型设置中检查接入状态。' };
10
+ }
11
+ return null;
12
+ }
13
+
14
+ module.exports = { modelProblem };
@@ -1,26 +1,26 @@
1
- 'use strict';
2
-
3
- const store = require('./store');
4
-
5
- /* ---------------- 敏感信息脱敏 ---------------- */
6
- function maskSensitive(text) {
7
- if (!text) return text;
8
- return String(text)
9
- .replace(/(?<!\d)\d{17}[\dXx](?!\d)/g, '******************')
10
- .replace(/(?<![A-Z0-9])[A-HJ-NPR-Z0-9]{17}(?![A-Z0-9])/gi, (m) => m.slice(0, 3) + '****' + m.slice(-4))
11
- .replace(/(?<!\d)1[3-9]\d{9}(?!\d)/g, (m) => m.slice(0, 3) + '****' + m.slice(-4));
12
- }
13
-
14
- function outbound(value, mask = store.getSetting('agent.maskSensitive', true)) {
15
- if (Array.isArray(value)) return value.map((item) => outbound(item, mask));
16
- if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [
17
- key, /^(?:api[_-]?key|authorization|secret|password|token)$/i.test(key) ? '[已隐藏]' : outbound(item, mask),
18
- ]));
19
- if (mask !== false && (typeof value === 'string' || typeof value === 'number')) {
20
- const text = maskSensitive(String(value));
21
- return text === String(value) ? value : text;
22
- }
23
- return value;
24
- }
25
-
26
- module.exports = { maskSensitive, outbound };
1
+ 'use strict';
2
+
3
+ const store = require('./store');
4
+
5
+ /* ---------------- 敏感信息脱敏 ---------------- */
6
+ function maskSensitive(text) {
7
+ if (!text) return text;
8
+ return String(text)
9
+ .replace(/(?<!\d)\d{17}[\dXx](?!\d)/g, '******************')
10
+ .replace(/(?<![A-Z0-9])[A-HJ-NPR-Z0-9]{17}(?![A-Z0-9])/gi, (m) => m.slice(0, 3) + '****' + m.slice(-4))
11
+ .replace(/(?<!\d)1[3-9]\d{9}(?!\d)/g, (m) => m.slice(0, 3) + '****' + m.slice(-4));
12
+ }
13
+
14
+ function outbound(value, mask = store.getSetting('agent.maskSensitive', true)) {
15
+ if (Array.isArray(value)) return value.map((item) => outbound(item, mask));
16
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [
17
+ key, /^(?:api[_-]?key|authorization|secret|password|token)$/i.test(key) ? '[已隐藏]' : outbound(item, mask),
18
+ ]));
19
+ if (mask !== false && (typeof value === 'string' || typeof value === 'number')) {
20
+ const text = maskSensitive(String(value));
21
+ return text === String(value) ? value : text;
22
+ }
23
+ return value;
24
+ }
25
+
26
+ module.exports = { maskSensitive, outbound };