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
@@ -1,57 +1,57 @@
1
- 'use strict';
2
-
3
- const {createCipheriv,createDecipheriv,randomBytes,scryptSync} = require('node:crypto');
4
- const context = Buffer.from('qip-workbench/signing-migration/v1');
5
- const uuid = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
6
- const limit = 8 * 1024 * 1024;
7
- function fail(message) { throw Object.assign(new Error(message),{status:400}); }
8
- function key(passphrase,salt) {
9
- if (typeof passphrase!=='string' || passphrase.length<16 || passphrase.length>160) fail('迁移口令须为 16~160 个字符');
10
- return scryptSync(passphrase,salt,32,{N:32768,maxmem:64*1024*1024});
11
- }
12
- function seal(directory,passphrase) {
13
- const bytes = Buffer.from(JSON.stringify(directory));
14
- if (bytes.length>limit) fail('人员目录超过迁移包大小限制');
15
- const salt=randomBytes(16);
16
- const iv=randomBytes(12);
17
- const cipher=createCipheriv('aes-256-gcm',key(passphrase,salt),iv);
18
- cipher.setAAD(context);
19
- const content=Buffer.concat([cipher.update(bytes),cipher.final()]);
20
- return Buffer.concat([Buffer.from([1]),salt,iv,cipher.getAuthTag(),content]);
21
- }
22
- function unseal(bytes,passphrase,members) {
23
- if (bytes.length<46 || bytes.length>limit+45 || bytes[0]!==1) fail('迁移包中的人员目录无效');
24
- const secret=key(passphrase,bytes.subarray(1,17));
25
- let data;
26
- try {
27
- const decipher=createDecipheriv('aes-256-gcm',secret,bytes.subarray(17,29));
28
- decipher.setAAD(context);
29
- decipher.setAuthTag(bytes.subarray(29,45));
30
- data=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(45)),decipher.final()]));
31
- } catch { fail('迁移口令不正确,或人员目录文件已损坏'); }
32
- if (!Array.isArray(data?.accounts) || !Array.isArray(data.delegations)) fail('人员目录结构不完整');
33
- const byId=new Map(members.map(({id,name})=>[id,name]));
34
- const people=new Map();
35
- const usernames=new Set();
36
- const memberIds=new Set();
37
- for (const account of data.accounts) {
38
- if (!uuid.test(account?.id) || people.has(account.id) || !['manager','worker'].includes(account.role) ||
39
- !/^[a-z0-9][a-z0-9._-]{2,39}$/.test(account.username) || usernames.has(account.username) ||
40
- memberIds.has(account.memberId) || byId.get(account.memberId)!==account.name ||
41
- !/^[a-f\d]{32}$/i.test(account.salt) || !/^[a-f\d]{128}$/i.test(account.passwordHash)) fail('人员目录与备份中的业务成员不一致');
42
- people.set(account.id,account);
43
- usernames.add(account.username);
44
- memberIds.add(account.memberId);
45
- }
46
- const grants=new Set();
47
- if (!data.accounts.some((account)=>account.role==='manager')) fail('人员目录须包含一位有效主管');
48
- for (const grant of data.delegations) {
49
- const principal=people.get(grant?.principalId);
50
- if (!uuid.test(grant?.id) || grants.has(grant.id) || !principal ||
51
- people.get(grant.deputyId)?.role!==principal.role || grant.principalId===grant.deputyId ||
52
- !Number.isFinite(Date.parse(grant.until))) fail('人员代理关系无效');
53
- grants.add(grant.id);
54
- }
55
- return data;
56
- }
57
- module.exports={seal,unseal};
1
+ 'use strict';
2
+
3
+ const {createCipheriv,createDecipheriv,randomBytes,scryptSync} = require('node:crypto');
4
+ const context = Buffer.from('qip-workbench/signing-migration/v1');
5
+ const uuid = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
6
+ const limit = 8 * 1024 * 1024;
7
+ function fail(message) { throw Object.assign(new Error(message),{status:400}); }
8
+ function key(passphrase,salt) {
9
+ if (typeof passphrase!=='string' || passphrase.length<16 || passphrase.length>160) fail('迁移口令须为 16~160 个字符');
10
+ return scryptSync(passphrase,salt,32,{N:32768,maxmem:64*1024*1024});
11
+ }
12
+ function seal(directory,passphrase) {
13
+ const bytes = Buffer.from(JSON.stringify(directory));
14
+ if (bytes.length>limit) fail('人员目录超过迁移包大小限制');
15
+ const salt=randomBytes(16);
16
+ const iv=randomBytes(12);
17
+ const cipher=createCipheriv('aes-256-gcm',key(passphrase,salt),iv);
18
+ cipher.setAAD(context);
19
+ const content=Buffer.concat([cipher.update(bytes),cipher.final()]);
20
+ return Buffer.concat([Buffer.from([1]),salt,iv,cipher.getAuthTag(),content]);
21
+ }
22
+ function unseal(bytes,passphrase,members) {
23
+ if (bytes.length<46 || bytes.length>limit+45 || bytes[0]!==1) fail('迁移包中的人员目录无效');
24
+ const secret=key(passphrase,bytes.subarray(1,17));
25
+ let data;
26
+ try {
27
+ const decipher=createDecipheriv('aes-256-gcm',secret,bytes.subarray(17,29));
28
+ decipher.setAAD(context);
29
+ decipher.setAuthTag(bytes.subarray(29,45));
30
+ data=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(45)),decipher.final()]));
31
+ } catch { fail('迁移口令不正确,或人员目录文件已损坏'); }
32
+ if (!Array.isArray(data?.accounts) || !Array.isArray(data.delegations)) fail('人员目录结构不完整');
33
+ const byId=new Map(members.map(({id,name})=>[id,name]));
34
+ const people=new Map();
35
+ const usernames=new Set();
36
+ const memberIds=new Set();
37
+ for (const account of data.accounts) {
38
+ if (!uuid.test(account?.id) || people.has(account.id) || !['manager','worker'].includes(account.role) ||
39
+ !/^[a-z0-9][a-z0-9._-]{2,39}$/.test(account.username) || usernames.has(account.username) ||
40
+ memberIds.has(account.memberId) || byId.get(account.memberId)!==account.name ||
41
+ !/^[a-f\d]{32}$/i.test(account.salt) || !/^[a-f\d]{128}$/i.test(account.passwordHash)) fail('人员目录与备份中的业务成员不一致');
42
+ people.set(account.id,account);
43
+ usernames.add(account.username);
44
+ memberIds.add(account.memberId);
45
+ }
46
+ const grants=new Set();
47
+ if (!data.accounts.some((account)=>account.role==='manager')) fail('人员目录须包含一位有效主管');
48
+ for (const grant of data.delegations) {
49
+ const principal=people.get(grant?.principalId);
50
+ if (!uuid.test(grant?.id) || grants.has(grant.id) || !principal ||
51
+ people.get(grant.deputyId)?.role!==principal.role || grant.principalId===grant.deputyId ||
52
+ !Number.isFinite(Date.parse(grant.until))) fail('人员代理关系无效');
53
+ grants.add(grant.id);
54
+ }
55
+ return data;
56
+ }
57
+ module.exports={seal,unseal};
@@ -1,225 +1,225 @@
1
- 'use strict';
2
-
3
- const { randomUUID } = require('node:crypto');
4
- const { AsyncLocalStorage } = require('node:async_hooks');
5
- const { outbound } = require('./privacy');
6
- const { modelProblem } = require('./model-error');
7
- const turns = new Map();
8
- const retention = 7 * 24 * 60 * 60 * 1000;
9
- const maxTurns = 40;
10
- const ownership = new AsyncLocalStorage();
11
- let persistence;
12
- const owner = () => ownership.getStore() || 'local';
13
- function configurePersistence(adapter) { persistence = adapter; }
14
- function withOwner(id, operation) { return ownership.run(id || 'local', operation); }
15
-
16
- function checkpoint(turn) {
17
- if (!turn.resumable || !persistence) return;
18
- try {
19
- if (turn.state === 'complete') persistence.remove(turn.id,turn.owner);
20
- else persistence.save(turn);
21
- } catch (error) { console.error('[qip-real-workbench] 保存续写进度失败:',error.code || error.name); }
22
- }
23
-
24
- function resolveTurn(id) {
25
- if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id)) return null;
26
- const saved = turns.get(id) || persistence?.load(id);
27
- if (!saved || saved.owner !== owner() || (!saved.active && Date.now()-saved.updatedAt >= retention)) return null;
28
- return saved;
29
- }
30
- const outputTokens = 8192;
31
- const passes = 4;
32
- const limitReasons = new Set(['max-tokens', 'length', 'max_tokens', 'max_output_tokens']);
33
-
34
- function isLimit(reason) { return limitReasons.has(reason); }
35
-
36
- function hidePrivateText(raw) {
37
- return String(raw || '').replace(/<(?:think|reasoning)\b[^>]*>[\s\S]*?(?:<\/(?:think|reasoning)>|$)/gi, '');
38
- }
39
-
40
- function protocolBody(raw) {
41
- const value = raw.trimStart();
42
- const fenced = /^(```|~~~)(?:json)?[ \t]*\r?\n/i.exec(value);
43
- const body = fenced && /^\s*\{/.test(value.slice(fenced[0].length))
44
- ? value.slice(fenced[0].length).replace(/\r?\n(?:```|~~~)\s*$/, '') : value;
45
- return /^\{\s*"(?:thought|reasoning|tool|args|final|answer|ready)"\s*(?::|$)/i.test(body) ||
46
- /^\{\s*"(?:thou|reas|too|arg|fin|ans|rea)[a-z]*$/i.test(body) ? body : null;
47
- }
48
-
49
- // Inspect spelling variants without normalizing legitimate text shown to the user.
50
- function containsToolProtocol(text) {
51
- const normalized = text.normalize('NFKC')
52
- .replace(/&(?:amp;)*(?:lt|#0*60|#x0*3c);/gi, '<')
53
- .replace(/&(?:amp;)*(?:gt|#0*62|#x0*3e);/gi, '>')
54
- .replace(/\\(?=[<"])/g, '');
55
- if (/\|\|\s*DSML\s*\|\||<\/?\s*(?:function[_ -]?(?:results?|calls?)|tool[_ -]?(?:results?|calls?)|已执行的工具调用与真实返回|已查询的证据)(?=[\s/>]|$)|<\|[^>\r\n]{0,48}(?:function|tool)[_ ▁-]?(?:calls?|outputs?|results?)/i.test(normalized)) return true;
56
- if (/^ *\[已执行的工具调用与真实返回\]|^\s*\[(?:真实返回|工具)\]\s*[\w{]|<\/?\s*(?:用户当前问题|检索资料|历史对话|业务台账快照)(?=[ >]|$)/im.test(normalized)) return true;
57
- return /\{\s*"(?:thought|reasoning|tool|args|ready|tool_calls|function_call)"\s*:/i.test(normalized) ||
58
- /<\/?\s*(?:function|tool)[_ -][a-z]*$/i.test(normalized.trimEnd());
59
- }
60
-
61
- function visibleAnswer(raw, complete = true) {
62
- const text = hidePrivateText(raw);
63
- const envelope = protocolBody(text);
64
- if (!envelope) return containsToolProtocol(text) ? '' : text;
65
- if (!complete) return '';
66
- try {
67
- const parsed = JSON.parse(envelope);
68
- if (!parsed.tool && typeof (parsed.final ?? parsed.answer) === 'string') {
69
- const answer = hidePrivateText(parsed.final ?? parsed.answer);
70
- return protocolBody(answer) || containsToolProtocol(answer) ? '' : answer;
71
- }
72
- } catch (_) { /* A truncated or malformed control message is hidden. */ }
73
- return '';
74
- }
75
-
76
- function continuation(previous, returned, anchor) {
77
- const next = returned.replace(/^[\r\n]*(?=\S)/u, '');
78
- if (returned.startsWith(anchor)) return returned.slice(anchor.length);
79
- if (next.startsWith(anchor)) return next.slice(anchor.length);
80
- const limit = Math.min(previous.length, anchor.length, returned.length);
81
- const minimum = Math.min(previous.length, 12);
82
- for (let n = limit; n >= minimum; n--) {
83
- if (previous.endsWith(returned.slice(0, n))) return returned.slice(n);
84
- }
85
- return null;
86
- }
87
-
88
- function keep(turn) {
89
- for (const [id, item] of turns) {
90
- if (!item.active && Date.now() - item.updatedAt >= retention) turns.delete(id);
91
- }
92
- if (turns.size >= maxTurns && !turns.has(turn.id)) {
93
- const oldest = [...turns].find(([, item]) => !item.active);
94
- if (oldest) turns.delete(oldest[0]);
95
- else return false;
96
- }
97
- turns.set(turn.id, turn);
98
- return true;
99
- }
100
-
101
- function snapshot(turn) {
102
- return {
103
- text: turn.text, state: turn.state, finishReason: turn.reason, model: turn.model,
104
- continuationCount: turn.calls > 0 ? turn.calls - 1 : 0, usage: turn.usage,
105
- ...(turn.resumable ? { answerId: turn.id } : {}),
106
- };
107
- }
108
-
109
- async function generate(turn, llm, { signal, onUpdate } = {}) {
110
- turn.active = true;
111
- turn.state = 'incomplete';
112
- let missed = 0;
113
- let retryBudget = false;
114
- try {
115
- for (let pass = 0; pass < passes; pass++) {
116
- signal?.throwIfAborted();
117
- const ongoing = turn.text.length > 0;
118
- const previous = outbound(turn.text.slice(-5500));
119
- const anchor = previous.slice(-96);
120
- const user = ongoing ? turn.user + '\n\n' + JSON.stringify({
121
- 已交付正文末段: previous,
122
- 精确衔接标记: anchor,
123
- 要求: '开头逐字输出精确衔接标记,保留其中所有换行和空格。紧接着从断点续写剩余正文,勿重复已交付内容。完成原问题所需全部章节,保持引用编号和 Markdown 表格结构。不要输出衔接说明。',
124
- }) : turn.user;
125
- const system = missed ? turn.system + '\n上一段未形成可交付的正文。重新按原问题直接写面向用户的回答,只用普通 Markdown,勿复述任何后台交互。' : turn.system;
126
- let part;
127
- try {
128
- turn.calls++;
129
- part = await llm.complete({
130
- system, user, signal, keepPartial: true,
131
- maxTokens: retryBudget || missed ? outputTokens * 2 : outputTokens,
132
- reasoning: retryBudget || ongoing || missed ? false : turn.reasoning,
133
- });
134
- } catch (error) {
135
- turn.reason = signal?.aborted ? 'aborted' : modelProblem(error)?.reason || 'interrupted';
136
- break;
137
- }
138
- turn.model = part.model || turn.model;
139
- turn.usage = part.usage || turn.usage;
140
- turn.reason = part.finishReason || 'interrupted';
141
- const natural = turn.reason === 'stop' && !signal?.aborted;
142
- if (['filtered', 'content-filter', 'content_filter', 'refusal'].includes(turn.reason)) break;
143
- const raw = visibleAnswer(part.text, natural);
144
- const append = raw && ongoing ? continuation(previous, raw, anchor) : raw;
145
- if (append && (ongoing || append.trim())) {
146
- const duplicate = ongoing && turn.text.endsWith(append);
147
- if (!duplicate) {
148
- turn.text += append;
149
- onUpdate?.(append, turn.resumable ? turn.id : undefined);
150
- missed = 0;
151
- retryBudget = false;
152
- } else {
153
- turn.reason = 'no-progress';
154
- if (++missed >= 2) break;
155
- continue;
156
- }
157
- } else {
158
- if (signal?.aborted) break;
159
- retryBudget = true;
160
- if (++missed >= 2) {
161
- if (natural) turn.reason = 'no-progress';
162
- break;
163
- }
164
- continue;
165
- }
166
- if (natural) { turn.state = 'complete'; break; }
167
- if (signal?.aborted || !isLimit(turn.reason)) break;
168
- }
169
- } catch (error) {
170
- if (!signal?.aborted) throw error;
171
- } finally {
172
- if (signal?.aborted && turn.state !== 'complete') turn.reason = 'aborted';
173
- turn.active = false;
174
- turn.updatedAt = Date.now();
175
- checkpoint(turn);
176
- console.info('[qip-real-workbench] 对话输出', JSON.stringify({
177
- state: turn.state, reason: turn.reason, calls: turn.calls, model: turn.model, usage: turn.usage,
178
- }));
179
- }
180
- return snapshot(turn);
181
- }
182
-
183
- function start(llm, options) {
184
- const turn = {
185
- id: randomUUID(), owner:owner(), system: options.system, user: options.user, reasoning: options.reasoning,
186
- questionOnly: options.questionOnly === true,
187
- text: '', model: null, reason: 'interrupted', active: false, calls: 0, updatedAt: Date.now(),
188
- };
189
- turn.resumable = keep(turn);
190
- if (turn.resumable) options.onStart?.(turn.id);
191
- return generate(turn, llm, options);
192
- }
193
-
194
- function discard(id) {
195
- const turn = resolveTurn(id);
196
- if (!turn) return;
197
- if (turn.active) throw Object.assign(new Error('这条回复正在续写,请等它结束后再删除。'),{status:409});
198
- persistence?.remove(id,turn.owner);
199
- turns.delete(id);
200
- }
201
- const hasActive = () => [...turns.values()].some((turn) => turn.active);
202
- const clear = () => turns.clear();
203
-
204
- function canResume(id) {
205
- const turn = resolveTurn(id);
206
- return !!turn && turn.state !== 'complete';
207
- }
208
-
209
- async function resume(llm, id, options) {
210
- const turn = resolveTurn(id);
211
- if (!turn) {
212
- throw Object.assign(new Error('续写已过期,请重新提问。'), { status: 410 });
213
- }
214
- if (turn.active) throw Object.assign(new Error('这条回复仍在生成,请稍后继续。'), { status: 409 });
215
- if (turn.state === 'complete') return snapshot(turn);
216
- const connector = turn.questionOnly ? options.questionModel : llm;
217
- if (!connector) {
218
- throw Object.assign(new Error(turn.questionOnly ? '暂时无法连接模型,请稍后继续。'
219
- : '续写需要使用这条回答的企业资料,请检查模型连接和模型数据权限。'), {status:503});
220
- }
221
- if (!keep(turn)) throw Object.assign(new Error('正在处理其他回复,请稍后继续。'),{status:409});
222
- return generate(turn, connector, options);
223
- }
224
-
225
- module.exports = { start, resume, canResume, discard, hasActive, clear, isLimit, visibleAnswer, configurePersistence, withOwner };
1
+ 'use strict';
2
+
3
+ const { randomUUID } = require('node:crypto');
4
+ const { AsyncLocalStorage } = require('node:async_hooks');
5
+ const { outbound } = require('./privacy');
6
+ const { modelProblem } = require('./model-error');
7
+ const turns = new Map();
8
+ const retention = 7 * 24 * 60 * 60 * 1000;
9
+ const maxTurns = 40;
10
+ const ownership = new AsyncLocalStorage();
11
+ let persistence;
12
+ const owner = () => ownership.getStore() || 'local';
13
+ function configurePersistence(adapter) { persistence = adapter; }
14
+ function withOwner(id, operation) { return ownership.run(id || 'local', operation); }
15
+
16
+ function checkpoint(turn) {
17
+ if (!turn.resumable || !persistence) return;
18
+ try {
19
+ if (turn.state === 'complete') persistence.remove(turn.id,turn.owner);
20
+ else persistence.save(turn);
21
+ } catch (error) { console.error('[qip-real-workbench] 保存续写进度失败:',error.code || error.name); }
22
+ }
23
+
24
+ function resolveTurn(id) {
25
+ if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id)) return null;
26
+ const saved = turns.get(id) || persistence?.load(id);
27
+ if (!saved || saved.owner !== owner() || (!saved.active && Date.now()-saved.updatedAt >= retention)) return null;
28
+ return saved;
29
+ }
30
+ const outputTokens = 8192;
31
+ const passes = 4;
32
+ const limitReasons = new Set(['max-tokens', 'length', 'max_tokens', 'max_output_tokens']);
33
+
34
+ function isLimit(reason) { return limitReasons.has(reason); }
35
+
36
+ function hidePrivateText(raw) {
37
+ return String(raw || '').replace(/<(?:think|reasoning)\b[^>]*>[\s\S]*?(?:<\/(?:think|reasoning)>|$)/gi, '');
38
+ }
39
+
40
+ function protocolBody(raw) {
41
+ const value = raw.trimStart();
42
+ const fenced = /^(```|~~~)(?:json)?[ \t]*\r?\n/i.exec(value);
43
+ const body = fenced && /^\s*\{/.test(value.slice(fenced[0].length))
44
+ ? value.slice(fenced[0].length).replace(/\r?\n(?:```|~~~)\s*$/, '') : value;
45
+ return /^\{\s*"(?:thought|reasoning|tool|args|final|answer|ready)"\s*(?::|$)/i.test(body) ||
46
+ /^\{\s*"(?:thou|reas|too|arg|fin|ans|rea)[a-z]*$/i.test(body) ? body : null;
47
+ }
48
+
49
+ // Inspect spelling variants without normalizing legitimate text shown to the user.
50
+ function containsToolProtocol(text) {
51
+ const normalized = text.normalize('NFKC')
52
+ .replace(/&(?:amp;)*(?:lt|#0*60|#x0*3c);/gi, '<')
53
+ .replace(/&(?:amp;)*(?:gt|#0*62|#x0*3e);/gi, '>')
54
+ .replace(/\\(?=[<"])/g, '');
55
+ if (/\|\|\s*DSML\s*\|\||<\/?\s*(?:function[_ -]?(?:results?|calls?)|tool[_ -]?(?:results?|calls?)|已执行的工具调用与真实返回|已查询的证据)(?=[\s/>]|$)|<\|[^>\r\n]{0,48}(?:function|tool)[_ ▁-]?(?:calls?|outputs?|results?)/i.test(normalized)) return true;
56
+ if (/^ *\[已执行的工具调用与真实返回\]|^\s*\[(?:真实返回|工具)\]\s*[\w{]|<\/?\s*(?:用户当前问题|检索资料|历史对话|业务台账快照)(?=[ >]|$)/im.test(normalized)) return true;
57
+ return /\{\s*"(?:thought|reasoning|tool|args|ready|tool_calls|function_call)"\s*:/i.test(normalized) ||
58
+ /<\/?\s*(?:function|tool)[_ -][a-z]*$/i.test(normalized.trimEnd());
59
+ }
60
+
61
+ function visibleAnswer(raw, complete = true) {
62
+ const text = hidePrivateText(raw);
63
+ const envelope = protocolBody(text);
64
+ if (!envelope) return containsToolProtocol(text) ? '' : text;
65
+ if (!complete) return '';
66
+ try {
67
+ const parsed = JSON.parse(envelope);
68
+ if (!parsed.tool && typeof (parsed.final ?? parsed.answer) === 'string') {
69
+ const answer = hidePrivateText(parsed.final ?? parsed.answer);
70
+ return protocolBody(answer) || containsToolProtocol(answer) ? '' : answer;
71
+ }
72
+ } catch (_) { /* A truncated or malformed control message is hidden. */ }
73
+ return '';
74
+ }
75
+
76
+ function continuation(previous, returned, anchor) {
77
+ const next = returned.replace(/^[\r\n]*(?=\S)/u, '');
78
+ if (returned.startsWith(anchor)) return returned.slice(anchor.length);
79
+ if (next.startsWith(anchor)) return next.slice(anchor.length);
80
+ const limit = Math.min(previous.length, anchor.length, returned.length);
81
+ const minimum = Math.min(previous.length, 12);
82
+ for (let n = limit; n >= minimum; n--) {
83
+ if (previous.endsWith(returned.slice(0, n))) return returned.slice(n);
84
+ }
85
+ return null;
86
+ }
87
+
88
+ function keep(turn) {
89
+ for (const [id, item] of turns) {
90
+ if (!item.active && Date.now() - item.updatedAt >= retention) turns.delete(id);
91
+ }
92
+ if (turns.size >= maxTurns && !turns.has(turn.id)) {
93
+ const oldest = [...turns].find(([, item]) => !item.active);
94
+ if (oldest) turns.delete(oldest[0]);
95
+ else return false;
96
+ }
97
+ turns.set(turn.id, turn);
98
+ return true;
99
+ }
100
+
101
+ function snapshot(turn) {
102
+ return {
103
+ text: turn.text, state: turn.state, finishReason: turn.reason, model: turn.model,
104
+ continuationCount: turn.calls > 0 ? turn.calls - 1 : 0, usage: turn.usage,
105
+ ...(turn.resumable ? { answerId: turn.id } : {}),
106
+ };
107
+ }
108
+
109
+ async function generate(turn, llm, { signal, onUpdate } = {}) {
110
+ turn.active = true;
111
+ turn.state = 'incomplete';
112
+ let missed = 0;
113
+ let retryBudget = false;
114
+ try {
115
+ for (let pass = 0; pass < passes; pass++) {
116
+ signal?.throwIfAborted();
117
+ const ongoing = turn.text.length > 0;
118
+ const previous = outbound(turn.text.slice(-5500));
119
+ const anchor = previous.slice(-96);
120
+ const user = ongoing ? turn.user + '\n\n' + JSON.stringify({
121
+ 已交付正文末段: previous,
122
+ 精确衔接标记: anchor,
123
+ 要求: '开头逐字输出精确衔接标记,保留其中所有换行和空格。紧接着从断点续写剩余正文,勿重复已交付内容。完成原问题所需全部章节,保持引用编号和 Markdown 表格结构。不要输出衔接说明。',
124
+ }) : turn.user;
125
+ const system = missed ? turn.system + '\n上一段未形成可交付的正文。重新按原问题直接写面向用户的回答,只用普通 Markdown,勿复述任何后台交互。' : turn.system;
126
+ let part;
127
+ try {
128
+ turn.calls++;
129
+ part = await llm.complete({
130
+ system, user, signal, keepPartial: true,
131
+ maxTokens: retryBudget || missed ? outputTokens * 2 : outputTokens,
132
+ reasoning: retryBudget || ongoing || missed ? false : turn.reasoning,
133
+ });
134
+ } catch (error) {
135
+ turn.reason = signal?.aborted ? 'aborted' : modelProblem(error)?.reason || 'interrupted';
136
+ break;
137
+ }
138
+ turn.model = part.model || turn.model;
139
+ turn.usage = part.usage || turn.usage;
140
+ turn.reason = part.finishReason || 'interrupted';
141
+ const natural = turn.reason === 'stop' && !signal?.aborted;
142
+ if (['filtered', 'content-filter', 'content_filter', 'refusal'].includes(turn.reason)) break;
143
+ const raw = visibleAnswer(part.text, natural);
144
+ const append = raw && ongoing ? continuation(previous, raw, anchor) : raw;
145
+ if (append && (ongoing || append.trim())) {
146
+ const duplicate = ongoing && turn.text.endsWith(append);
147
+ if (!duplicate) {
148
+ turn.text += append;
149
+ onUpdate?.(append, turn.resumable ? turn.id : undefined);
150
+ missed = 0;
151
+ retryBudget = false;
152
+ } else {
153
+ turn.reason = 'no-progress';
154
+ if (++missed >= 2) break;
155
+ continue;
156
+ }
157
+ } else {
158
+ if (signal?.aborted) break;
159
+ retryBudget = true;
160
+ if (++missed >= 2) {
161
+ if (natural) turn.reason = 'no-progress';
162
+ break;
163
+ }
164
+ continue;
165
+ }
166
+ if (natural) { turn.state = 'complete'; break; }
167
+ if (signal?.aborted || !isLimit(turn.reason)) break;
168
+ }
169
+ } catch (error) {
170
+ if (!signal?.aborted) throw error;
171
+ } finally {
172
+ if (signal?.aborted && turn.state !== 'complete') turn.reason = 'aborted';
173
+ turn.active = false;
174
+ turn.updatedAt = Date.now();
175
+ checkpoint(turn);
176
+ console.info('[qip-real-workbench] 对话输出', JSON.stringify({
177
+ state: turn.state, reason: turn.reason, calls: turn.calls, model: turn.model, usage: turn.usage,
178
+ }));
179
+ }
180
+ return snapshot(turn);
181
+ }
182
+
183
+ function start(llm, options) {
184
+ const turn = {
185
+ id: randomUUID(), owner:owner(), system: options.system, user: options.user, reasoning: options.reasoning,
186
+ questionOnly: options.questionOnly === true,
187
+ text: '', model: null, reason: 'interrupted', active: false, calls: 0, updatedAt: Date.now(),
188
+ };
189
+ turn.resumable = keep(turn);
190
+ if (turn.resumable) options.onStart?.(turn.id);
191
+ return generate(turn, llm, options);
192
+ }
193
+
194
+ function discard(id) {
195
+ const turn = resolveTurn(id);
196
+ if (!turn) return;
197
+ if (turn.active) throw Object.assign(new Error('这条回复正在续写,请等它结束后再删除。'),{status:409});
198
+ persistence?.remove(id,turn.owner);
199
+ turns.delete(id);
200
+ }
201
+ const hasActive = () => [...turns.values()].some((turn) => turn.active);
202
+ const clear = () => turns.clear();
203
+
204
+ function canResume(id) {
205
+ const turn = resolveTurn(id);
206
+ return !!turn && turn.state !== 'complete';
207
+ }
208
+
209
+ async function resume(llm, id, options) {
210
+ const turn = resolveTurn(id);
211
+ if (!turn) {
212
+ throw Object.assign(new Error('续写已过期,请重新提问。'), { status: 410 });
213
+ }
214
+ if (turn.active) throw Object.assign(new Error('这条回复仍在生成,请稍后继续。'), { status: 409 });
215
+ if (turn.state === 'complete') return snapshot(turn);
216
+ const connector = turn.questionOnly ? options.questionModel : llm;
217
+ if (!connector) {
218
+ throw Object.assign(new Error(turn.questionOnly ? '暂时无法连接模型,请稍后继续。'
219
+ : '续写需要使用这条回答的企业资料,请检查模型连接和模型数据权限。'), {status:503});
220
+ }
221
+ if (!keep(turn)) throw Object.assign(new Error('正在处理其他回复,请稍后继续。'),{status:409});
222
+ return generate(turn, connector, options);
223
+ }
224
+
225
+ module.exports = { start, resume, canResume, discard, hasActive, clear, isLimit, visibleAnswer, configurePersistence, withOwner };