settings.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. 'use strict';
  2. // 系统设置:模型列表、配置读写(脱敏)、生图/对话 API 连通性测试
  3. const fs = require('fs');
  4. const path = require('path');
  5. const https = require('https');
  6. const { URL } = require('url');
  7. const { sendJson, readBody } = require('../util.js');
  8. const { DEFAULT_CHAT_MODEL } = require('../context.js');
  9. function register(app, ctx) {
  10. app.get('/api/models', async ({ res }) => {
  11. sendJson(res, 200, { models: ctx.models.MODELS, default: ctx.config.model });
  12. });
  13. app.get('/api/settings', async ({ res }) => {
  14. sendJson(res, 200, {
  15. apiKey: ctx.config.apiKey ? ctx.config.apiKey.slice(0, 8) + '••••••••' : '',
  16. apiBase: ctx.config.apiBase,
  17. model: ctx.config.model,
  18. rootDir: ctx.workspace.getWorkspaceRoot(),
  19. pageSize: ctx.config.pageSize,
  20. delayMs: ctx.config.delayMs,
  21. cookieConfigured: !!ctx.session.cookie && !!ctx.session.getKsid(),
  22. port: ctx.config.port,
  23. chatModel: ctx.config.chatModel || '',
  24. chatApiBase: ctx.config.chatApiBase || ctx.config.apiBase,
  25. chatApiKey: ctx.config.chatApiKey ? ctx.config.chatApiKey.slice(0, 8) + '••••••••' : '',
  26. chatKeyFallback: !ctx.config.chatApiKey && !!ctx.config.apiKey,
  27. autoSyncEnabled: !!(ctx.config.autoSync && ctx.config.autoSync.enabled),
  28. autoSyncTime: (ctx.config.autoSync && ctx.config.autoSync.time) || '06:00',
  29. accessTokenSet: !!ctx.config.accessToken,
  30. aitableEnabled: !!(ctx.config.aitable && ctx.config.aitable.enabled),
  31. aitableAppKey: (ctx.config.aitable && ctx.config.aitable.appKey) || '',
  32. aitableBaseId: (ctx.config.aitable && ctx.config.aitable.baseId) || '',
  33. aitableSheetName: (ctx.config.aitable && ctx.config.aitable.sheetName) || '经营数据',
  34. aitableSecretSet: !!(ctx.config.aitable && ctx.config.aitable.appSecret),
  35. });
  36. });
  37. app.post('/api/settings', async ({ req, res }) => {
  38. const body = await readBody(req);
  39. const config = ctx.config;
  40. const previousApiKey = config.apiKey;
  41. const previousCookie = ctx.session.cookie;
  42. if (body.apiKey && !body.apiKey.includes('••••')) config.apiKey = body.apiKey;
  43. if (body.model && ctx.models.MODEL_IDS.has(body.model)) config.model = body.model;
  44. if (body.rootDir) {
  45. const rootDir = path.resolve(String(body.rootDir).trim());
  46. if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
  47. return sendJson(res, 400, { error: '输出根目录不存在: ' + rootDir });
  48. }
  49. config.rootDir = rootDir;
  50. }
  51. if (body.pageSize !== undefined) {
  52. const pageSize = Number(body.pageSize);
  53. if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) {
  54. return sendJson(res, 400, { error: '每页条数必须为 1-200 的整数' });
  55. }
  56. config.pageSize = pageSize;
  57. }
  58. if (body.delayMs !== undefined) {
  59. const delayMs = Number(body.delayMs);
  60. if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 60000) {
  61. return sendJson(res, 400, { error: '间隔必须为 0-60000 毫秒' });
  62. }
  63. config.delayMs = delayMs;
  64. }
  65. if (body.chatModel !== undefined) config.chatModel = String(body.chatModel).trim();
  66. if (body.chatApiBase !== undefined) config.chatApiBase = String(body.chatApiBase).trim();
  67. if (body.chatApiKey !== undefined && !String(body.chatApiKey).includes('••••')) config.chatApiKey = String(body.chatApiKey).trim();
  68. if (body.autoSyncEnabled !== undefined || body.autoSyncTime !== undefined) {
  69. if (!config.autoSync || typeof config.autoSync !== 'object') config.autoSync = { enabled: false, time: '06:00' };
  70. if (body.autoSyncEnabled !== undefined) config.autoSync.enabled = !!body.autoSyncEnabled;
  71. if (body.autoSyncTime !== undefined) {
  72. const t = String(body.autoSyncTime).trim();
  73. const hm = /^\d{1,2}:\d{2}$/.test(t) ? t.split(':').map(Number) : null;
  74. if (!hm || hm[0] > 23 || hm[1] > 59) {
  75. return sendJson(res, 400, { error: '自动同步时间格式应为 HH:mm' });
  76. }
  77. config.autoSync.time = t;
  78. }
  79. }
  80. if (body.accessToken !== undefined) {
  81. const t = String(body.accessToken).trim();
  82. if (t === '-') config.accessToken = ''; // 约定:输入 - 清除口令
  83. else if (t) config.accessToken = t;
  84. }
  85. if (body.aitableEnabled !== undefined || body.aitableAppKey !== undefined || body.aitableBaseId !== undefined || body.aitableSheetName !== undefined || body.aitableAppSecret !== undefined) {
  86. if (!config.aitable || typeof config.aitable !== 'object') config.aitable = { enabled: false, appKey: '', appSecret: '', baseId: '', sheetName: '经营数据' };
  87. if (body.aitableEnabled !== undefined) config.aitable.enabled = !!body.aitableEnabled;
  88. if (body.aitableAppKey !== undefined) config.aitable.appKey = String(body.aitableAppKey).trim();
  89. if (body.aitableBaseId !== undefined) config.aitable.baseId = String(body.aitableBaseId).trim();
  90. if (body.aitableSheetName !== undefined) config.aitable.sheetName = String(body.aitableSheetName).trim() || '经营数据';
  91. if (body.aitableAppSecret !== undefined) {
  92. const sec = String(body.aitableAppSecret).trim();
  93. if (sec === '-') config.aitable.appSecret = ''; // 约定:输入 - 清除
  94. else if (sec) config.aitable.appSecret = sec;
  95. }
  96. }
  97. ctx.saveConfig();
  98. if (body.cookie !== undefined) {
  99. ctx.session.cookie = body.cookie;
  100. ctx.session.saveSession();
  101. }
  102. ctx.logs.pushSystemLog(
  103. `系统设置已保存:模型=${config.model},根目录=${config.rootDir},每页=${config.pageSize},间隔=${config.delayMs}ms` +
  104. (previousApiKey !== config.apiKey ? ',API Key 已更新' : '') +
  105. (body.cookie !== undefined && previousCookie !== ctx.session.cookie ? ',Cookie 已更新' : ''),
  106. 'success'
  107. );
  108. sendJson(res, 200, { ok: true });
  109. });
  110. // 生图 API 连通性测试:GET /v1/models(轻量、不产生生图费用)
  111. app.post('/api/image/test', async ({ res }) => {
  112. return new Promise((resolve) => {
  113. let base;
  114. try { base = new URL(ctx.config.apiBase); } catch { return sendJson(res, 400, { error: 'API 地址不合法: ' + ctx.config.apiBase }); }
  115. const options = {
  116. hostname: base.hostname, port: base.port || 443, path: '/v1/models', method: 'GET',
  117. headers: { Authorization: `Bearer ${ctx.config.apiKey}` }, timeout: 15000,
  118. };
  119. const up = https.request(options, (upRes) => {
  120. const chunks = [];
  121. upRes.on('data', (c) => chunks.push(c));
  122. upRes.on('end', () => {
  123. let json = null;
  124. try { json = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* 保留空 */ }
  125. const models = json && Array.isArray(json.data) ? json.data.map((m) => (m && m.id) || '').filter(Boolean) : null;
  126. sendJson(res, 200, { statusCode: upRes.statusCode, models, modelFound: !!(models && models.includes(ctx.config.model)), model: ctx.config.model });
  127. });
  128. });
  129. up.on('error', (e) => sendJson(res, 200, { statusCode: 0, error: e.message || String(e) }));
  130. up.on('timeout', () => up.destroy(new Error('请求超时')));
  131. up.end();
  132. });
  133. });
  134. app.post('/api/chat/test', async ({ req, res }) => {
  135. const body = await readBody(req);
  136. const nlQuery = require('../../nl-query.js');
  137. const cfg = {
  138. chatApiBase: body.chatApiBase || ctx.config.chatApiBase || ctx.config.apiBase,
  139. chatApiKey: (body.chatApiKey && !String(body.chatApiKey).includes('••••')) ? body.chatApiKey : (ctx.config.chatApiKey || ctx.config.apiKey),
  140. chatModel: body.chatModel || ctx.config.chatModel || DEFAULT_CHAT_MODEL,
  141. };
  142. try {
  143. const reply = await nlQuery.ping(cfg);
  144. sendJson(res, 200, { ok: true, reply });
  145. } catch (e) {
  146. sendJson(res, 502, { error: e.message });
  147. }
  148. });
  149. }
  150. module.exports = { register };