dsh-vt-web-chat 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +66 -33
  2. package/client.js +355 -798
  3. package/docs/research/01-chat-demo-embedding.md +322 -0
  4. package/index.js +36 -8
  5. package/locale/en.json +1 -1
  6. package/locale/zh.json +1 -1
  7. package/package.json +15 -6
  8. package/scripts/dev-server.mjs +54 -0
  9. package/scripts/sync-upstream.mjs +106 -0
  10. package/src/auth.js +65 -0
  11. package/src/maintenance.js +240 -0
  12. package/src/proxy.js +139 -0
  13. package/src/route.js +307 -0
  14. package/src/settings.js +74 -0
  15. package/webview/UPSTREAM.json +6 -0
  16. package/webview/dist/LICENSE +21 -0
  17. package/webview/dist/index.html +1 -0
  18. package/webview/dist/static/css/async/4959.1382f613.css +1 -0
  19. package/webview/dist/static/css/main.27198ffe.css +1 -0
  20. package/webview/dist/static/js/async/1031.575fa503.js +1 -0
  21. package/webview/dist/static/js/async/1085.769e13d5.js +1 -0
  22. package/webview/dist/static/js/async/1086.4d3be1fa.js +1 -0
  23. package/webview/dist/static/js/async/1097.4f798919.js +117 -0
  24. package/webview/dist/static/js/async/1299.0ef86619.js +1 -0
  25. package/webview/dist/static/js/async/1393.6ef1efab.js +1 -0
  26. package/webview/dist/static/js/async/1401.88487cba.js +1 -0
  27. package/webview/dist/static/js/async/1505.8913966f.js +1 -0
  28. package/webview/dist/static/js/async/160.81018107.js +55 -0
  29. package/webview/dist/static/js/async/1679.153f9f03.js +1 -0
  30. package/webview/dist/static/js/async/1690.fe25bdfe.js +1 -0
  31. package/webview/dist/static/js/async/2110.a1d33f2f.js +215 -0
  32. package/webview/dist/static/js/async/2152.97b0a90c.js +1 -0
  33. package/webview/dist/static/js/async/2168.9925ab2d.js +1 -0
  34. package/webview/dist/static/js/async/2312.4fd0ef8e.js +1 -0
  35. package/webview/dist/static/js/async/2348.41564e59.js +148 -0
  36. package/webview/dist/static/js/async/2356.631a6aca.js +1 -0
  37. package/webview/dist/static/js/async/2415.00900482.js +1 -0
  38. package/webview/dist/static/js/async/2461.15199935.js +1 -0
  39. package/webview/dist/static/js/async/2541.f8eac009.js +1 -0
  40. package/webview/dist/static/js/async/2607.abb8bc11.js +1 -0
  41. package/webview/dist/static/js/async/265.b43cee3f.js +1 -0
  42. package/webview/dist/static/js/async/2696.60d5ecf0.js +1 -0
  43. package/webview/dist/static/js/async/3014.c8e9b88f.js +1 -0
  44. package/webview/dist/static/js/async/3111.e2cca965.js +1 -0
  45. package/webview/dist/static/js/async/3251.0b9c608e.js +1 -0
  46. package/webview/dist/static/js/async/3339.ed293391.js +1 -0
  47. package/webview/dist/static/js/async/3376.3aa54d1a.js +93 -0
  48. package/webview/dist/static/js/async/3465.845187e8.js +1 -0
  49. package/webview/dist/static/js/async/3477.94bd21ab.js +5 -0
  50. package/webview/dist/static/js/async/3594.edfe4411.js +1 -0
  51. package/webview/dist/static/js/async/3806.28abb895.js +1 -0
  52. package/webview/dist/static/js/async/3909.4b4bd806.js +1 -0
  53. package/webview/dist/static/js/async/4138.104dbc81.js +1 -0
  54. package/webview/dist/static/js/async/426.6fedaabe.js +1 -0
  55. package/webview/dist/static/js/async/4387.151c5858.js +1 -0
  56. package/webview/dist/static/js/async/4468.d0c907eb.js +1 -0
  57. package/webview/dist/static/js/async/4471.b0874c8d.js +158 -0
  58. package/webview/dist/static/js/async/4568.cf5e547d.js +1 -0
  59. package/webview/dist/static/js/async/4580.f1bc120a.js +131 -0
  60. package/webview/dist/static/js/async/4695.8f4b8910.js +1 -0
  61. package/webview/dist/static/js/async/4959.deb41780.js +1 -0
  62. package/webview/dist/static/js/async/509.f3e093b4.js +59 -0
  63. package/webview/dist/static/js/async/5172.e1e3bd11.js +43 -0
  64. package/webview/dist/static/js/async/535.e10ba324.js +1 -0
  65. package/webview/dist/static/js/async/5546.89da376c.js +24 -0
  66. package/webview/dist/static/js/async/5597.3018e134.js +36 -0
  67. package/webview/dist/static/js/async/5636.61075f0b.js +174 -0
  68. package/webview/dist/static/js/async/5638.7cfdcd7e.js +1 -0
  69. package/webview/dist/static/js/async/5706.d34ac064.js +1 -0
  70. package/webview/dist/static/js/async/5856.d75c4e3b.js +1 -0
  71. package/webview/dist/static/js/async/6061.7cfcc3e9.js +1 -0
  72. package/webview/dist/static/js/async/6152.d3a64904.js +1 -0
  73. package/webview/dist/static/js/async/6297.6e694780.js +1 -0
  74. package/webview/dist/static/js/async/6325.cafe9e55.js +1 -0
  75. package/webview/dist/static/js/async/6332.682f48c9.js +1 -0
  76. package/webview/dist/static/js/async/6349.e9992b47.js +56 -0
  77. package/webview/dist/static/js/async/6389.1bb952e3.js +1 -0
  78. package/webview/dist/static/js/async/6443.95da1923.js +1 -0
  79. package/webview/dist/static/js/async/6526.56ce7dc4.js +1 -0
  80. package/webview/dist/static/js/async/6600.6e0dfb69.js +1 -0
  81. package/webview/dist/static/js/async/6689.d0bd8935.js +262 -0
  82. package/webview/dist/static/js/async/6751.54c80aba.js +1 -0
  83. package/webview/dist/static/js/async/680.5aa7dcb4.js +1 -0
  84. package/webview/dist/static/js/async/6948.9cd716f4.js +1 -0
  85. package/webview/dist/static/js/async/7262.f680270f.js +88 -0
  86. package/webview/dist/static/js/async/7515.20c14480.js +1 -0
  87. package/webview/dist/static/js/async/7536.34769b35.js +1 -0
  88. package/webview/dist/static/js/async/7630.ed725458.js +1 -0
  89. package/webview/dist/static/js/async/7853.0a4b794a.js +1 -0
  90. package/webview/dist/static/js/async/8180.4d4299ef.js +1 -0
  91. package/webview/dist/static/js/async/828.56686119.js +1 -0
  92. package/webview/dist/static/js/async/8379.1b75211c.js +1 -0
  93. package/webview/dist/static/js/async/8389.4f120664.js +1 -0
  94. package/webview/dist/static/js/async/8538.d5f92d14.js +24 -0
  95. package/webview/dist/static/js/async/8560.1bdf90ec.js +1 -0
  96. package/webview/dist/static/js/async/8794.759831e8.js +60 -0
  97. package/webview/dist/static/js/async/8821.2b444259.js +29 -0
  98. package/webview/dist/static/js/async/925.548cc1b9.js +1 -0
  99. package/webview/dist/static/js/async/9252.3c22a9cd.js +1 -0
  100. package/webview/dist/static/js/async/9261.1e796956.js +1 -0
  101. package/webview/dist/static/js/async/9324.b3518ebf.js +1 -0
  102. package/webview/dist/static/js/async/9354.4425ac3c.js +1 -0
  103. package/webview/dist/static/js/async/9501.a7851380.js +4 -0
  104. package/webview/dist/static/js/async/9560.d604e606.js +166 -0
  105. package/webview/dist/static/js/async/9640.5f6a6734.js +1 -0
  106. package/webview/dist/static/js/async/9765.ecc8b5dc.js +1 -0
  107. package/webview/dist/static/js/async/9821.b1897048.js +63 -0
  108. package/webview/dist/static/js/main.7c5f914e.js +3 -0
  109. package/webview/dist/static/media/KaTeX_AMS-Regular.1608a09b.woff +0 -0
  110. package/webview/dist/static/media/KaTeX_AMS-Regular.4aafdb68.ttf +0 -0
  111. package/webview/dist/static/media/KaTeX_AMS-Regular.a79f1c31.woff2 +0 -0
  112. package/webview/dist/static/media/KaTeX_Caligraphic-Bold.b6770918.woff +0 -0
  113. package/webview/dist/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf +0 -0
  114. package/webview/dist/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2 +0 -0
  115. package/webview/dist/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf +0 -0
  116. package/webview/dist/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2 +0 -0
  117. package/webview/dist/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff +0 -0
  118. package/webview/dist/static/media/KaTeX_Fraktur-Bold.9f256b85.woff +0 -0
  119. package/webview/dist/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf +0 -0
  120. package/webview/dist/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2 +0 -0
  121. package/webview/dist/static/media/KaTeX_Fraktur-Regular.7c187121.woff +0 -0
  122. package/webview/dist/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2 +0 -0
  123. package/webview/dist/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf +0 -0
  124. package/webview/dist/static/media/KaTeX_Main-Bold.b74a1a8b.ttf +0 -0
  125. package/webview/dist/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2 +0 -0
  126. package/webview/dist/static/media/KaTeX_Main-Bold.d181c465.woff +0 -0
  127. package/webview/dist/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2 +0 -0
  128. package/webview/dist/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf +0 -0
  129. package/webview/dist/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff +0 -0
  130. package/webview/dist/static/media/KaTeX_Main-Italic.47373d1e.ttf +0 -0
  131. package/webview/dist/static/media/KaTeX_Main-Italic.8916142b.woff2 +0 -0
  132. package/webview/dist/static/media/KaTeX_Main-Italic.9024d815.woff +0 -0
  133. package/webview/dist/static/media/KaTeX_Main-Regular.0462f03b.woff2 +0 -0
  134. package/webview/dist/static/media/KaTeX_Main-Regular.7f51fe03.woff +0 -0
  135. package/webview/dist/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf +0 -0
  136. package/webview/dist/static/media/KaTeX_Math-BoldItalic.572d331f.woff2 +0 -0
  137. package/webview/dist/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf +0 -0
  138. package/webview/dist/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff +0 -0
  139. package/webview/dist/static/media/KaTeX_Math-Italic.5295ba48.woff +0 -0
  140. package/webview/dist/static/media/KaTeX_Math-Italic.939bc644.ttf +0 -0
  141. package/webview/dist/static/media/KaTeX_Math-Italic.f28c23ac.woff2 +0 -0
  142. package/webview/dist/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2 +0 -0
  143. package/webview/dist/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf +0 -0
  144. package/webview/dist/static/media/KaTeX_SansSerif-Bold.bf59d231.woff +0 -0
  145. package/webview/dist/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2 +0 -0
  146. package/webview/dist/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff +0 -0
  147. package/webview/dist/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf +0 -0
  148. package/webview/dist/static/media/KaTeX_SansSerif-Regular.74048478.woff +0 -0
  149. package/webview/dist/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2 +0 -0
  150. package/webview/dist/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf +0 -0
  151. package/webview/dist/static/media/KaTeX_Script-Regular.03e9641d.woff2 +0 -0
  152. package/webview/dist/static/media/KaTeX_Script-Regular.07505710.woff +0 -0
  153. package/webview/dist/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf +0 -0
  154. package/webview/dist/static/media/KaTeX_Size1-Regular.e1e279cb.woff +0 -0
  155. package/webview/dist/static/media/KaTeX_Size1-Regular.eae34984.woff2 +0 -0
  156. package/webview/dist/static/media/KaTeX_Size1-Regular.fabc004a.ttf +0 -0
  157. package/webview/dist/static/media/KaTeX_Size2-Regular.57727022.woff +0 -0
  158. package/webview/dist/static/media/KaTeX_Size2-Regular.5916a24f.woff2 +0 -0
  159. package/webview/dist/static/media/KaTeX_Size2-Regular.d6b476ec.ttf +0 -0
  160. package/webview/dist/static/media/KaTeX_Size3-Regular.9acaf01c.woff +0 -0
  161. package/webview/dist/static/media/KaTeX_Size3-Regular.a144ef58.ttf +0 -0
  162. package/webview/dist/static/media/KaTeX_Size3-Regular.b4230e7e.woff2 +0 -0
  163. package/webview/dist/static/media/KaTeX_Size4-Regular.10d95fd3.woff2 +0 -0
  164. package/webview/dist/static/media/KaTeX_Size4-Regular.7a996c9d.woff +0 -0
  165. package/webview/dist/static/media/KaTeX_Size4-Regular.fbccdabe.ttf +0 -0
  166. package/webview/dist/static/media/KaTeX_Typewriter-Regular.6258592b.woff +0 -0
  167. package/webview/dist/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2 +0 -0
  168. package/webview/dist/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf +0 -0
package/src/auth.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * DeepSeek 上游凭据解析。
3
+ *
4
+ * 顺序与 `dsh-vt-quick-chat` 保持一致:先账号授权,再 API Key。
5
+ * 账号授权不需要用户另存密钥,退出登录后自动落到 API Key。
6
+ *
7
+ * 这里的 token 只在 Host 半边使用,绝不下发到浏览器。
8
+ */
9
+ const DEEPSEEK_BASE_URL = 'https://api.deepseek.com';
10
+
11
+ /** 账号授权 token 的请求头;由 `dsh-llm-deepseek-account` 定义。 */
12
+ const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token';
13
+
14
+ /** API Key 的凭据名;与 DSH 模型设置里的默认引用一致。 */
15
+ const API_KEY_REF = 'DEEPSEEK_API_KEY';
16
+
17
+ /**
18
+ * 解析一次上游请求要用的凭据。
19
+ * @param ctx - Host 插件上下文。
20
+ * @param baseURL - 推理源根地址,用于账号 token 的归属校验。
21
+ * @returns `{ via, headers }`;没有可用凭据时返回 undefined。
22
+ */
23
+ export async function resolveAuth(ctx, baseURL = DEEPSEEK_BASE_URL) {
24
+ const account = safeGet(ctx, 'deepseekAccount');
25
+ if (account !== undefined && typeof account.resolveToken === 'function') {
26
+ try {
27
+ // resolveToken 校验目标地址是否属于推理源;传真实请求地址,语义最直接。
28
+ const token = await account.resolveToken(`${baseURL}/anthropic/v1/messages`);
29
+ if (typeof token === 'string' && token.length > 0) {
30
+ return { via: 'account', headers: { [ACCOUNT_TOKEN_HEADER]: token } };
31
+ }
32
+ } catch {
33
+ // 未登录、授权失效或地址不被允许:继续尝试 API Key。
34
+ }
35
+ }
36
+ const credentials = safeGet(ctx, 'credentials');
37
+ if (credentials !== undefined && typeof credentials.resolve === 'function') {
38
+ try {
39
+ const hit = await credentials.resolve(API_KEY_REF);
40
+ const value = hit?.value;
41
+ if (typeof value === 'string' && value.length > 0) {
42
+ return { via: 'api-key', headers: { 'x-api-key': value, authorization: `Bearer ${value}` } };
43
+ }
44
+ } catch {
45
+ // 凭证服务不可用:交给调用方给 401。
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /**
52
+ * 取可选服务;缺服务只是少一条路,不是错误。
53
+ * @param ctx - Host 插件上下文。
54
+ * @param name - 服务名。
55
+ * @returns 服务实例或 undefined。
56
+ */
57
+ export function safeGet(ctx, name) {
58
+ try {
59
+ return ctx.get(name);
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ export { DEEPSEEK_BASE_URL, ACCOUNT_TOKEN_HEADER };
@@ -0,0 +1,240 @@
1
+ /**
2
+ * 入口页注入:会话保留策略、默认收起侧栏、DSH 悬浮岛避让。
3
+ *
4
+ * 为什么清理必须发生在前端启动之前:对话列表在启动时读一次 IndexedDB,
5
+ * 清理放晚会让用户先看到即将被删的会话,再在列表里凭空消失。
6
+ * `chat-demo` 的产物只有一个 defer 入口脚本,所以把入口脚本摘下、清理完再挂回去,
7
+ * 顺序就确定了,而且不需要改上游任何源码。
8
+ */
9
+ const DB_NAME = 'chat-demo';
10
+
11
+ /**
12
+ * 生成注入到 `index.html` 的内联脚本。
13
+ * @param appSrc - 前端入口脚本地址;null 表示没找到入口,清理不阻塞启动。
14
+ * @param capability - 面板能力令牌,随每个 `/webchat/` 请求回传。
15
+ * @returns 内联脚本文本。
16
+ */
17
+ export function bootstrapScript(appSrc, capability) {
18
+ return `(function () {
19
+ var APP_SRC = ${JSON.stringify(appSrc)};
20
+ var CAP = ${JSON.stringify(typeof capability === 'string' ? capability : '')};
21
+ var DB = ${JSON.stringify(DB_NAME)};
22
+ var DAY = 86400000;
23
+ var log = function (message, detail) {
24
+ try { console.info('[webchat] ' + message, detail === undefined ? '' : detail); } catch (error) {}
25
+ };
26
+
27
+ // 面板的每个请求都带上能力令牌:这样宿主不必区分浏览器 Cookie、桌面壳 IPC 或
28
+ // cross-site 判定,只要令牌对得上、来源在回环,就放行。
29
+ if (CAP) {
30
+ try {
31
+ var nativeFetch = window.fetch.bind(window);
32
+ window.fetch = function (input, init) {
33
+ try {
34
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
35
+ if (url.indexOf('/webchat/') === 0 || url.indexOf(window.location.origin + '/webchat/') === 0) {
36
+ var headers = new Headers((init && init.headers) || (input && input.headers) || undefined);
37
+ headers.set('x-vtwc-cap', CAP);
38
+ init = Object.assign({}, init, { headers: headers });
39
+ }
40
+ } catch (error) {}
41
+ return nativeFetch(input, init);
42
+ };
43
+ } catch (error) {}
44
+ }
45
+
46
+ function boot() {
47
+ if (!APP_SRC) return;
48
+ var script = document.createElement('script');
49
+ script.src = APP_SRC;
50
+ script.async = false;
51
+ document.body.appendChild(script);
52
+ }
53
+
54
+ function openDatabase() {
55
+ return new Promise(function (resolve, reject) {
56
+ var request = indexedDB.open(DB);
57
+ request.onsuccess = function () { resolve(request.result); };
58
+ request.onerror = function () { reject(request.error); };
59
+ request.onblocked = function () { reject(new Error('database blocked')); };
60
+ });
61
+ }
62
+
63
+ function allSummaries(db) {
64
+ return new Promise(function (resolve, reject) {
65
+ var tx = db.transaction('sessionSummaries', 'readonly');
66
+ var request = tx.objectStore('sessionSummaries').getAll();
67
+ request.onsuccess = function () { resolve(request.result || []); };
68
+ request.onerror = function () { reject(request.error); };
69
+ });
70
+ }
71
+
72
+ function deleteExpired(db, expired, deadFiles) {
73
+ return new Promise(function (resolve, reject) {
74
+ var tx = db.transaction(['sessions', 'sessionSummaries', 'files'], 'readwrite');
75
+ var summaries = tx.objectStore('sessionSummaries');
76
+ var sessions = tx.objectStore('sessions');
77
+ var files = tx.objectStore('files');
78
+ expired.forEach(function (summary) {
79
+ sessions.delete(summary.id);
80
+ summaries.delete(summary.id);
81
+ });
82
+ deadFiles.forEach(function (id) { files.delete(id); });
83
+ tx.oncomplete = function () { resolve(); };
84
+ tx.onerror = function () { reject(tx.error); };
85
+ tx.onabort = function () { reject(tx.error); };
86
+ });
87
+ }
88
+
89
+ /**
90
+ * 删除 updatedAt 早于截止时间的会话,以及因此不再被引用的本地附件原件。
91
+ * 判断全部在事务外算好,事务里只发同步请求,避免事务提前失活。
92
+ */
93
+ async function prune(days) {
94
+ if (typeof indexedDB === 'undefined') return 0;
95
+ // 库还不存在时不要凭空建一个空库,交给前端自己创建。
96
+ if (typeof indexedDB.databases === 'function') {
97
+ var databases = await indexedDB.databases();
98
+ if (!databases.some(function (entry) { return entry && entry.name === DB; })) return 0;
99
+ }
100
+ var db = await openDatabase();
101
+ try {
102
+ if (!db.objectStoreNames.contains('sessionSummaries')) return 0;
103
+ var cutoff = Date.now() - days * DAY;
104
+ var summaries = await allSummaries(db);
105
+ var expired = [];
106
+ var alive = [];
107
+ summaries.forEach(function (summary) {
108
+ var stamp = typeof summary.updatedAt === 'number' ? summary.updatedAt : summary.createdAt;
109
+ if (typeof stamp === 'number' && stamp < cutoff) expired.push(summary);
110
+ else alive.push(summary);
111
+ });
112
+ if (expired.length === 0) return 0;
113
+
114
+ var keep = new Set();
115
+ alive.forEach(function (summary) {
116
+ (Array.isArray(summary.fileIds) ? summary.fileIds : []).forEach(function (id) { keep.add(id); });
117
+ });
118
+ var deadFiles = [];
119
+ expired.forEach(function (summary) {
120
+ (Array.isArray(summary.fileIds) ? summary.fileIds : []).forEach(function (id) {
121
+ if (!keep.has(id)) deadFiles.push(id);
122
+ });
123
+ });
124
+ await deleteExpired(db, expired, deadFiles);
125
+ return expired.length;
126
+ } finally {
127
+ try { db.close(); } catch (error) {}
128
+ }
129
+ }
130
+
131
+ // 跟随宿主语言:只在用户还没在前端里选过语言时写入,之后以前端自己的设置为准。
132
+ try {
133
+ var lang = new URLSearchParams(window.location.search).get('lang');
134
+ if (lang && !window.localStorage.getItem('chat-demo:locale')) {
135
+ window.localStorage.setItem('chat-demo:locale', lang);
136
+ }
137
+ } catch (error) {}
138
+
139
+ // 面板是主内容区的一块画布,默认不展开自己的侧栏:先把舞台让给对话。
140
+ // 只强制一次(升级到本版本时),之后完全尊重用户在前端里的手动展开/收起。
141
+ try {
142
+ if (window.localStorage.getItem('vtwc:sider-default-applied') === null) {
143
+ window.localStorage.setItem('chat-demo:sider-collapsed', 'true');
144
+ window.localStorage.setItem('vtwc:sider-default-applied', '1');
145
+ }
146
+ } catch (error) {}
147
+
148
+ // DSH 悬浮岛避让:宿主量出顶部被占的高度后发过来,这里只负责落成 CSS 变量。
149
+ (function installSeatBridge() {
150
+ var root = document.documentElement;
151
+ function siderState() {
152
+ var frame = document.querySelector('#root > [class*="frame-"]');
153
+ var sider = frame === null ? null : frame.querySelector('[class*="sider-"]');
154
+ root.setAttribute('data-vtwc-sider', sider === null ? 'collapsed' : 'open');
155
+ }
156
+ function apply(inset) {
157
+ if (typeof inset !== 'number' || !isFinite(inset) || inset <= 0) {
158
+ root.removeAttribute('data-vtwc-seat');
159
+ root.style.removeProperty('--vtwc-seat');
160
+ } else {
161
+ root.setAttribute('data-vtwc-seat', '');
162
+ root.style.setProperty('--vtwc-seat', Math.round(inset) + 'px');
163
+ }
164
+ siderState();
165
+ }
166
+ window.addEventListener('message', function (event) {
167
+ var data = event.data;
168
+ if (data && data.type === 'vt-webchat:seat') apply(data.inset);
169
+ });
170
+ siderState();
171
+ var frame = document.querySelector('#root > [class*="frame-"]');
172
+ if (frame !== null && typeof MutationObserver === 'function') {
173
+ new MutationObserver(siderState).observe(frame, { childList: true });
174
+ }
175
+ try {
176
+ parent.postMessage({ type: 'vt-webchat:hello' }, '*');
177
+ } catch (error) {}
178
+ })();
179
+
180
+ // 网页版的设置项里有一个 API Key 输入;请求其实由宿主代发,这里给一个占位值,
181
+ // 让前端跳过首次使用的引导,用户也不需要看到一把假密钥的来源。
182
+ try {
183
+ if (!window.localStorage.getItem('chat-demo:api-key')) {
184
+ window.localStorage.setItem('chat-demo:api-key', 'managed-by-dsh');
185
+ }
186
+ } catch (error) {}
187
+
188
+ var settings = fetch('/webchat/api/settings', { headers: { accept: 'application/json' } })
189
+ .then(function (response) { return response.ok ? response.json() : null; })
190
+ .then(function (value) {
191
+ var days = value && typeof value.retentionDays === 'number' ? value.retentionDays : 30;
192
+ return days > 0 ? days : 0;
193
+ })
194
+ .catch(function () { return 30; });
195
+
196
+ // 清理最多等 3 秒:存储异常时宁可这次不清理,也不能让面板一直白屏。
197
+ Promise.race([
198
+ settings.then(function (days) { return days > 0 ? prune(days) : 0; }),
199
+ new Promise(function (resolve) { setTimeout(function () { resolve(-1); }, 3000); }),
200
+ ])
201
+ .then(function (removed) {
202
+ window.__vtWebChatRetention = { removed: removed };
203
+ if (removed > 0) log('retention removed sessions', removed);
204
+ else if (removed === -1) log('retention skipped: storage timeout');
205
+ })
206
+ .catch(function (error) {
207
+ var message = String(error && error.message ? error.message : error);
208
+ window.__vtWebChatRetention = { removed: -2, error: message };
209
+ log('retention failed', message);
210
+ })
211
+ .then(boot);
212
+ })();`;
213
+ }
214
+
215
+ /**
216
+ * 悬浮岛避让样式。
217
+ *
218
+ * DSH 的 `shell.leading` 座位(docs:`--dsh-frame-leading-clearance`)在侧栏收起时
219
+ * 覆盖在主面板左上角。面板是 iframe,拿不到宿主的 CSS 变量,所以由父页量出座位底部,
220
+ * 这里把它落成:整块应用下移同样的高度、并在顶部补出与左右两栏一致的底色。
221
+ * 只用 `#root > [class*="frame-"]` 这一条结构选择器,不依赖上游的哈希类名。
222
+ */
223
+ const SEAT_STYLE = `<style id="vtwc-seat">html[data-vtwc-seat] #root > [class*="frame-"]{top:calc(var(--app-viewport-top,0px) + var(--vtwc-seat,0px))!important;height:calc(var(--app-viewport-height,100dvh) - var(--vtwc-seat,0px))!important}html[data-vtwc-seat]{background:var(--dsw-alias-bg-base)}html[data-vtwc-seat][data-vtwc-sider="open"]{background:linear-gradient(to right,var(--dsw-specific-sidebar-fill) 0 261px,var(--dsw-alias-bg-base) 261px)}</style>`;
224
+
225
+ /**
226
+ * 把启动闸门注入入口页:摘掉前端入口脚本,换成注入脚本在清理后挂回。
227
+ * @param html - 原始 index.html 文本。
228
+ * @returns `{ html, gated }`;`gated` 表示是否成功接管了入口脚本。
229
+ */
230
+ export function injectBootstrap(html, capability) {
231
+ const entry = /<script\b[^>]*\bsrc="([^"]+)"[^>]*>\s*<\/script>/iu.exec(html);
232
+ const appSrc = entry === null ? null : entry[1];
233
+ const stripped = entry === null ? html : html.replace(entry[0], '');
234
+ const tag = `<script>${bootstrapScript(appSrc, capability)}</script>`;
235
+ const withStyle = /<\/head>/iu.test(stripped) ? stripped.replace(/<\/head>/iu, `${SEAT_STYLE}</head>`) : `${SEAT_STYLE}${stripped}`;
236
+ const injected = /<\/body>/iu.test(withStyle)
237
+ ? withStyle.replace(/<\/body>/iu, `${tag}</body>`)
238
+ : `${withStyle}${tag}`;
239
+ return { html: injected, gated: appSrc !== null };
240
+ }
package/src/proxy.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * 把浏览器发到插件路由的请求转给 DeepSeek,并注入宿主凭据。
3
+ *
4
+ * 边界:浏览器只认识 `/webchat/<path>`,永远拿不到 token;
5
+ * 上游地址由宿主拼回 `https://api.deepseek.com/<path>`。
6
+ */
7
+ import { Readable } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
9
+ import { DEEPSEEK_BASE_URL, resolveAuth } from './auth.js';
10
+
11
+ /** 不向上游转发的逐跳头。 */
12
+ const HOP_BY_HOP = new Set([
13
+ 'connection',
14
+ 'keep-alive',
15
+ 'proxy-authenticate',
16
+ 'proxy-authorization',
17
+ 'te',
18
+ 'trailer',
19
+ 'transfer-encoding',
20
+ 'upgrade',
21
+ 'host',
22
+ 'content-length',
23
+ 'cookie',
24
+ ]);
25
+
26
+ /**
27
+ * 把 Headers 之外的请求头收敛成可转发的普通对象。
28
+ * @param req - Node 请求。
29
+ * @returns 小写键名的新对象。
30
+ */
31
+ function forwardableHeaders(req) {
32
+ const headers = {};
33
+ for (const [name, value] of Object.entries(req.headers)) {
34
+ if (HOP_BY_HOP.has(name) || value === undefined) continue;
35
+ headers[name] = Array.isArray(value) ? value.join(', ') : value;
36
+ }
37
+ return headers;
38
+ }
39
+
40
+ /**
41
+ * 转发一次请求。
42
+ * @param ctx - Host 插件上下文。
43
+ * @param req - Node 请求。
44
+ * @param res - Node 响应。
45
+ * @param options - `{ baseURL, pathname, search }`;pathname 含 `/webchat` 前缀。
46
+ * @returns 无返回;响应已写回。
47
+ */
48
+ export async function proxyRequest(ctx, req, res, { baseURL = DEEPSEEK_BASE_URL, pathname, search = '' }) {
49
+ const auth = await resolveAuth(ctx, baseURL);
50
+ if (auth === undefined) {
51
+ writeJson(res, 401, {
52
+ type: 'error',
53
+ error: {
54
+ type: 'authentication_error',
55
+ message:
56
+ '当前 DSH 没有可用的 DeepSeek 凭据:请先登录 DeepSeek 账户,或在「设置 → 模型」里配置 DeepSeek API Key。',
57
+ },
58
+ });
59
+ return;
60
+ }
61
+
62
+ const upstreamPath = pathname.slice('/webchat'.length) || '/';
63
+ const target = `${baseURL.replace(/\/+$/u, '')}${upstreamPath}${search}`;
64
+ const method = (req.method ?? 'GET').toUpperCase();
65
+
66
+ // 聊天的 SSE 会持续很久;客户端离开面板时必须一起取消,否则请求会挂在上游。
67
+ const controller = new AbortController();
68
+ const onClose = () => {
69
+ if (!res.writableEnded) controller.abort();
70
+ };
71
+ res.on('close', onClose);
72
+
73
+ const headers = {
74
+ 'anthropic-version': '2023-06-01',
75
+ 'anthropic-beta': typeof req.headers['anthropic-beta'] === 'string' ? req.headers['anthropic-beta'] : 'files-api-2025-04-14',
76
+ ...forwardableHeaders(req),
77
+ ...auth.headers,
78
+ };
79
+ if (headers.accept === undefined) headers.accept = 'text/event-stream';
80
+ // SSE 必须逐块到达浏览器;请求上游压缩会让整段响应被攒起来,还容易和头部转发脱节。
81
+ headers['accept-encoding'] = 'identity';
82
+
83
+ const init = { method, headers, signal: controller.signal };
84
+ if (method !== 'GET' && method !== 'HEAD') {
85
+ // 文件上传是 multipart,可能是几十 MB:直接流式转发,不读进内存。
86
+ init.body = Readable.toWeb(req);
87
+ init.duplex = 'half';
88
+ }
89
+
90
+ let upstream;
91
+ try {
92
+ upstream = await fetch(target, init);
93
+ } catch (error) {
94
+ if (controller.signal.aborted) return;
95
+ writeJson(res, 502, {
96
+ type: 'error',
97
+ error: { type: 'api_error', message: `无法连接 DeepSeek:${error instanceof Error ? error.message : String(error)}` },
98
+ });
99
+ return;
100
+ }
101
+
102
+ const responseHeaders = {
103
+ 'cache-control': 'no-store',
104
+ 'x-accel-buffering': 'no',
105
+ };
106
+ const contentType = upstream.headers.get('content-type');
107
+ if (contentType !== null) responseHeaders['content-type'] = contentType;
108
+ // 万一上游无视 identity 仍然压缩,编码头必须一起转发,否则浏览器拿到的是二进制。
109
+ const encoding = upstream.headers.get('content-encoding');
110
+ if (encoding !== null) responseHeaders['content-encoding'] = encoding;
111
+ res.writeHead(upstream.status, responseHeaders);
112
+
113
+ if (upstream.body === null || method === 'HEAD') {
114
+ res.end();
115
+ return;
116
+ }
117
+ try {
118
+ await pipeline(Readable.fromWeb(upstream.body), res);
119
+ } catch {
120
+ // 客户端中途关闭:上游已被 abort,这里只需收掉响应。
121
+ if (!res.writableEnded) res.destroy();
122
+ }
123
+ }
124
+
125
+ /**
126
+ * 写一个 JSON 响应。
127
+ * @param res - Node 响应。
128
+ * @param status - HTTP 状态码。
129
+ * @param value - 可序列化对象。
130
+ */
131
+ export function writeJson(res, status, value) {
132
+ const body = JSON.stringify(value);
133
+ res.writeHead(status, {
134
+ 'content-type': 'application/json; charset=utf-8',
135
+ 'cache-control': 'no-store',
136
+ 'content-length': Buffer.byteLength(body),
137
+ });
138
+ res.end(body);
139
+ }