codexmate 0.1.38 → 0.1.40

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 (40) hide show
  1. package/README.md +1 -1
  2. package/README.vi.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/cli/doctor-core.js +1 -1
  5. package/cli.js +93 -79
  6. package/lib/model-test.js +126 -21
  7. package/lib/shared-knowledge.js +86 -0
  8. package/package.json +5 -1
  9. package/plugins/prompt-templates/overview.mjs +1 -7
  10. package/web-ui/app.js +3 -2
  11. package/web-ui/index.html +2 -0
  12. package/web-ui/modules/app.computed.main-tabs.mjs +3 -0
  13. package/web-ui/modules/app.methods.navigation.mjs +2 -1
  14. package/web-ui/modules/i18n/locales/en.mjs +1969 -2018
  15. package/web-ui/modules/i18n/locales/expand.mjs +18 -0
  16. package/web-ui/modules/i18n/locales/ja.mjs +1970 -2019
  17. package/web-ui/modules/i18n/locales/keys.mjs +1969 -0
  18. package/web-ui/modules/i18n/locales/vi.mjs +1969 -1987
  19. package/web-ui/modules/i18n/locales/zh-tw.mjs +1969 -2016
  20. package/web-ui/modules/i18n/locales/zh.mjs +1968 -2016
  21. package/web-ui/modules/model-test.mjs +114 -26
  22. package/web-ui/modules/shared-knowledge.mjs +139 -0
  23. package/web-ui/partials/index/layout-header.html +22 -5
  24. package/web-ui/partials/index/panel-knowledge.html +68 -0
  25. package/web-ui/partials/index/panel-plugins.html +12 -27
  26. package/web-ui/partials/index/plugin-file-sharing.html +1 -1
  27. package/web-ui/partials/index/routing-model-test.html +29 -9
  28. package/web-ui/res/reicon-knowledge.LICENSE.txt +20 -0
  29. package/web-ui/res/reicon-knowledge.svg +18 -0
  30. package/web-ui/res/web-ui-render.precompiled.js +1 -14783
  31. package/web-ui/styles/base-theme.css +2 -2
  32. package/web-ui/styles/navigation-panels.css +11 -18
  33. package/web-ui/styles/plugins-panel.css +16 -91
  34. package/web-ui/styles/responsive.css +8 -16
  35. package/web-ui/styles/routing.css +8 -0
  36. package/web-ui/styles/shared-knowledge.css +227 -0
  37. package/web-ui/styles/sub-tabs.css +13 -0
  38. package/web-ui/styles/theme-violet.css +0 -21
  39. package/web-ui/styles/titles-cards.css +0 -23
  40. package/web-ui/styles.css +1 -0
package/README.md CHANGED
@@ -150,7 +150,7 @@ Choose Light, Dark, Ocean or Violet in Settings. Violet adapts [Catppuccin Latte
150
150
  <a id="routing-groups"></a>
151
151
  ### Model test
152
152
 
153
- The selected Codex/Pi subtab is saved and restored after reload. Choose a provider and model from existing configuration, enter a message and send it. View the Markdown reply, returned model ID and response time in seconds. Tests consume API credits without starting CLIs, changing configuration or saving test history. Each test sends one request without retries, sets no local response deadline and limits output to 2048 tokens. Supports configured Responses, Chat Completions, Completions and Anthropic Messages; native login and command-based credentials are not integrated. Group settings are no longer shown in the Web UI; existing backend routing and OpenAI Chat API behavior is unchanged. See the [Web UI guide](https://sakurabytecore.github.io/codexmate/guide/web-ui).
153
+ The selected Codex/Pi subtab is saved and restored after reload. Choose a provider and model from existing configuration, enter a message and send it. View the Markdown reply, returned model ID and response time in seconds. Tests consume API credits without starting CLIs, changing configuration or saving test history. Choose **All** in the model list, then submit to read the selected provider’s full model catalog. After confirmation, it sends the same message once per model and shows each result, even when some tests fail. Generation requests are not retried, have no local response deadline and limit output to 2048 tokens. Supports configured Responses, Chat Completions, Completions and Anthropic Messages; native login and command-based credentials are not integrated. Group settings are no longer shown in the Web UI; existing backend routing and OpenAI Chat API behavior is unchanged. See the [Web UI guide](https://sakurabytecore.github.io/codexmate/guide/web-ui).
154
154
 
155
155
  Tests use Codex UA/Originator or Pi SDK headers, with configured UA overrides taking priority. They read Codex reasoning/output settings and Pi model token limits and compatibility flags. If the installed client version cannot be resolved, requests identify as versioned CodexMate tests rather than inventing a client version.
156
156
 
package/README.vi.md CHANGED
@@ -150,7 +150,7 @@ Chọn Sáng, Tối, Đại dương hoặc Tím dịu trong phần cài đặt.
150
150
  <a id="nhóm-định-tuyến"></a>
151
151
  ### Kiểm thử mô hình
152
152
 
153
- Lựa chọn tab Codex/Pi được lưu và khôi phục sau khi tải lại. Chọn nhà cung cấp và mô hình trong cấu hình hiện có, nhập nội dung rồi gửi. Xem câu trả lời Markdown, ID mô hình trả về và thời gian tính bằng giây. Kiểm thử tiêu thụ hạn mức API; không mở CLI, đổi cấu hình hoặc lưu lịch sử. Mỗi lần chỉ gửi một yêu cầu, không tự thử lại, không đặt thời hạn phản hồi cục bộ và giới hạn đầu ra 2048 token. Hỗ trợ Responses, Chat Completions, Completions và Anthropic Messages đã cấu hình; chưa tích hợp đăng nhập gốc hoặc khóa lấy bằng lệnh. Web không còn hiển thị cài đặt nhóm; chức năng phân phối phía máy chủ và OpenAI Chat API giữ nguyên. Xem [hướng dẫn Web UI](https://sakurabytecore.github.io/codexmate/guide/web-ui).
153
+ Lựa chọn tab Codex/Pi được lưu và khôi phục sau khi tải lại. Chọn nhà cung cấp và mô hình trong cấu hình hiện có, nhập nội dung rồi gửi. Xem câu trả lời Markdown, ID mô hình trả về và thời gian tính bằng giây. Kiểm thử tiêu thụ hạn mức API; không mở CLI, đổi cấu hình hoặc lưu lịch sử. Chọn **Tất cả** trong danh sách mô hình rồi gửi để đọc toàn bộ danh mục của nhà cung cấp đã chọn. Sau khi xác nhận, hệ thống gửi cùng một tin nhắn một lần cho từng mô hình và hiển thị từng kết quả, kể cả khi có lỗi. Yêu cầu tạo phản hồi không tự thử lại, không đặt thời hạn cục bộ và giới hạn đầu ra 2048 token. Hỗ trợ Responses, Chat Completions, Completions và Anthropic Messages đã cấu hình; chưa tích hợp đăng nhập gốc hoặc khóa lấy bằng lệnh. Web không còn hiển thị cài đặt nhóm; chức năng phân phối phía máy chủ và OpenAI Chat API giữ nguyên. Xem [hướng dẫn Web UI](https://sakurabytecore.github.io/codexmate/guide/web-ui).
154
154
 
155
155
  Yêu cầu kiểm thử dùng UA/Originator của Codex hoặc header SDK của Pi; UA đã cấu hình được ưu tiên. Đọc thiết lập suy luận/đầu ra Codex và giới hạn token, tham số tương thích của mô hình Pi. Nếu không đọc được phiên bản khách đã cài, yêu cầu dùng định danh kiểm thử CodexMate có phiên bản, không giả tạo phiên bản khách.
156
156
 
package/README.zh.md CHANGED
@@ -150,7 +150,7 @@ Codex Mate 管理已有工具和本地记录,不是新的 AI 模型,也不
150
150
  <a id="路由组"></a>
151
151
  ### 模型测试
152
152
 
153
- Codex/Pi 子页签选择会保存,刷新后恢复。选择已有配置中的供应商与模型,手动输入问题后发送。查看 Markdown 回复、返回模型 ID 与耗时秒数。测试消耗 API 额度;不启动 CLI、不改配置、不保存测试记录。单次只发一个请求,不自动重试,不设本地响应超时,输出上限 2048 Token。支持配置中的 Responses、Chat Completions、Completions 与 Anthropic Messages;原生登录与命令式凭据暂不接入。Web 已移除模型组设置入口,已有后端分配与 OpenAI Chat API 保持原行为。详见 [Web UI 指南](https://sakurabytecore.github.io/codexmate/guide/web-ui)。
153
+ Codex/Pi 子页签选择会保存,刷新后恢复。选择已有配置中的供应商与模型,手动输入问题后发送。查看 Markdown 回复、返回模型 ID 与耗时秒数。测试消耗 API 额度;不启动 CLI、不改配置、不保存测试记录。在「模型」下拉中选择「全部」,再点「发送测试」,即可读取所选供应商的完整模型目录。确认后,每个模型接收一次相同内容,单项失败不阻断后续测试。生成请求不自动重试,不设本地响应超时,输出上限 2048 Token。支持配置中的 Responses、Chat Completions、Completions 与 Anthropic Messages;原生登录与命令式凭据暂不接入。Web 已移除模型组设置入口,已有后端分配与 OpenAI Chat API 保持原行为。详见 [Web UI 指南](https://sakurabytecore.github.io/codexmate/guide/web-ui)。
154
154
 
155
155
  测试请求使用 Codex UA/Originator 或 Pi 的 SDK 请求头,已有自定义 UA 优先。读取 Codex 的推理/输出配置及 Pi 模型的 Token 上限与兼容参数。无法读取客户端版本时使用带版本的 CodexMate 测试标识,不伪造客户端版本。
156
156
 
@@ -536,7 +536,7 @@ async function buildDoctorReport(params = {}, deps = {}) {
536
536
 
537
537
  sources.status = getStatusPayload();
538
538
  if (options.includeInstall !== false) {
539
- sources.install = buildInstallStatusReport();
539
+ sources.install = await buildInstallStatusReport();
540
540
  }
541
541
 
542
542
  if (buildConfigHealthReport) {
package/cli.js CHANGED
@@ -12,7 +12,10 @@ const JSON5 = require('json5');
12
12
  const zipLib = require('zip-lib');
13
13
  const yauzl = require('yauzl');
14
14
  const zlib = require('node:zlib');
15
- const { exec, execSync, execFileSync, spawn, spawnSync } = require('child_process');
15
+ const { exec, execFile, execSync, execFileSync, spawn, spawnSync } = require('child_process');
16
+ const { promisify } = require('util');
17
+ const execAsync = promisify(exec);
18
+ const execFileAsync = promisify(execFile);
16
19
  const http = require('http');
17
20
  const https = require('https');
18
21
  const net = require('net');
@@ -149,6 +152,7 @@ const { createPluginConfigController } = require('./cli/plugin-config');
149
152
  const { createSessionContextHealthController } = require('./lib/session-context-health');
150
153
  const { createSessionUsageReportController, exportSessionUsageReport } = require('./lib/session-usage-report');
151
154
  const { createSessionFeatures } = require('./lib/session-features');
155
+ const { createSharedKnowledge } = require('./lib/shared-knowledge');
152
156
  const { listHandoffs } = require('./lib/thread-handoff');
153
157
  const { discoverServers, probeServer } = require('./lib/handoff-mcp');
154
158
  const {
@@ -513,7 +517,7 @@ function getModelTestProviders(target) {
513
517
  const key = typeof provider.apiKey === 'string' ? provider.apiKey.trim() : '';
514
518
  const models = Array.isArray(provider.models) ? provider.models : [];
515
519
  return { name, baseUrl: provider.baseUrl, api: apis[provider.api] || provider.api,
516
- apiKey: process.env[key] || key, headers: provider.headers,
520
+ apiKey: process.env[key] || key, headers: provider.headers, compat: provider.compat,
517
521
  error: key.startsWith('!') ? '命令式凭据暂不支持真实测试,请使用已有环境变量配置' : '',
518
522
  models: models.map(model => model.id).filter(id => typeof id === 'string' && id.trim()),
519
523
  modelOptions: Object.fromEntries(models.filter(model => model && model.id).map(model => [model.id, {
@@ -1172,7 +1176,7 @@ function normalizeSettingsTabPreference(value) {
1172
1176
 
1173
1177
  function normalizeMainTabPreference(value) {
1174
1178
  const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
1175
- const allowed = new Set(['dashboard', 'config', 'routing', 'sessions', 'usage', 'market', 'plugins', 'docs', 'settings', 'trash', 'prompts']);
1179
+ const allowed = new Set(['dashboard', 'config', 'routing', 'sessions', 'usage', 'market', 'plugins', 'docs', 'settings', 'trash', 'prompts', 'knowledge']);
1176
1180
  return allowed.has(normalized) ? normalized : 'dashboard';
1177
1181
  }
1178
1182
 
@@ -10037,6 +10041,7 @@ const { readSessionContextHealth, readSessionContextNode, iterateSessionContextN
10037
10041
 
10038
10042
  const sessionUsageReport = createSessionUsageReportController({ fs, listSessionUsage, iterateSessionUsageRecords });
10039
10043
 
10044
+ const sharedKnowledge = createSharedKnowledge(path.join(CODEXMATE_DIR, 'shared-knowledge.json'));
10040
10045
  const sessionFeatures = createSessionFeatures({ root: path.join(CODEXMATE_DIR, 'session-features'),
10041
10046
  usageReport: sessionUsageReport,
10042
10047
  readNode: readSessionContextNode, nodes: iterateSessionContextNodes,
@@ -13415,7 +13420,7 @@ function isPrivateNetworkHost(hostname) {
13415
13420
  return false;
13416
13421
  }
13417
13422
 
13418
- function detectPreferredPackageManager() {
13423
+ async function detectPreferredPackageManager() {
13419
13424
  const userAgent = typeof process.env.npm_config_user_agent === 'string'
13420
13425
  ? process.env.npm_config_user_agent.trim().toLowerCase()
13421
13426
  : '';
@@ -13423,8 +13428,14 @@ function detectPreferredPackageManager() {
13423
13428
  if (userAgent.startsWith('bun/')) return 'bun';
13424
13429
  if (userAgent.startsWith('npm/')) return 'npm';
13425
13430
 
13426
- if (commandExists('pnpm', '--version')) return 'pnpm';
13427
- if (commandExists('bun', '--version')) return 'bun';
13431
+ for (const manager of ['pnpm', 'bun']) {
13432
+ const options = { windowsHide: true, timeout: 5000 };
13433
+ try {
13434
+ if (process.platform === 'win32') await execAsync(`${manager} --version`, options);
13435
+ else await execFileAsync(manager, ['--version'], options);
13436
+ return manager;
13437
+ } catch (_) { /* Try the next available package manager. */ }
13438
+ }
13428
13439
  return 'npm';
13429
13440
  }
13430
13441
 
@@ -13450,12 +13461,14 @@ function resolveCommandPath(command) {
13450
13461
  }
13451
13462
  }
13452
13463
 
13453
- function resolveSpawnCommand(command) {
13454
- if (!command) return '';
13455
- if (process.platform === 'win32') {
13456
- return command;
13464
+ async function locateInstallBinary(command) {
13465
+ const locator = process.platform === 'win32' ? 'where' : 'which';
13466
+ try {
13467
+ const { stdout } = await execFileAsync(locator, [command], { windowsHide: true, timeout: 2500 });
13468
+ return stdout.split(/\r?\n/).map(line => line.trim()).find(Boolean) || '';
13469
+ } catch (_) {
13470
+ return '';
13457
13471
  }
13458
- return resolveCommandPath(command) || command;
13459
13472
  }
13460
13473
 
13461
13474
  function parseBinaryVersionOutput(text) {
@@ -13468,71 +13481,45 @@ function parseBinaryVersionOutput(text) {
13468
13481
  return line.length > 120 ? `${line.slice(0, 117)}...` : line;
13469
13482
  }
13470
13483
 
13471
- function probeCliBinary(binName) {
13472
- const attempts = [['--version'], ['-v'], ['version']];
13484
+ async function probeCliBinary(binName) {
13485
+ const isWindows = process.platform === 'win32';
13486
+ const executable = isWindows ? binName : (await locateInstallBinary(binName) || binName);
13487
+ const options = { windowsHide: true, timeout: 5000 };
13473
13488
  let lastError = '';
13474
13489
 
13475
- for (const args of attempts) {
13490
+ for (const flag of ['--version', '-v', 'version']) {
13491
+ let output;
13476
13492
  try {
13477
- let output = '';
13478
- let status = 0;
13479
- if (process.platform === 'win32') {
13480
- const argString = args.join(' ').trim();
13481
- const commandLine = argString ? `${binName} ${argString}` : binName;
13482
- const stdout = execSync(commandLine, {
13483
- encoding: 'utf8',
13484
- windowsHide: true,
13485
- timeout: 5000,
13486
- stdio: ['ignore', 'pipe', 'pipe'],
13487
- shell: true
13488
- });
13489
- output = String(stdout || '');
13493
+ if (isWindows) {
13494
+ const { stdout } = await execAsync(`${executable} ${flag}`, options);
13495
+ output = stdout;
13490
13496
  } else {
13491
- const cmd = resolveSpawnCommand(binName);
13492
- const probe = spawnSync(cmd, args, {
13493
- encoding: 'utf8',
13494
- windowsHide: true,
13495
- timeout: 5000,
13496
- stdio: ['ignore', 'pipe', 'pipe']
13497
- });
13498
- status = Number.isFinite(probe.status) ? probe.status : (probe.error ? 1 : 0);
13499
- output = `${probe.stdout || ''}\n${probe.stderr || ''}`.trim();
13497
+ const { stdout, stderr } = await execFileAsync(executable, [flag], options);
13498
+ output = `${stdout}\n${stderr}`;
13500
13499
  }
13501
- const version = parseBinaryVersionOutput(output);
13502
- return {
13503
- installed: true,
13504
- bin: binName,
13505
- version: version || 'unknown',
13506
- path: resolveCommandPath(binName),
13507
- error: ''
13508
- };
13509
13500
  } catch (error) {
13510
- const err = error || {};
13511
- const stdout = typeof err.stdout === 'string' ? err.stdout : String(err.stdout || '');
13512
- const stderr = typeof err.stderr === 'string' ? err.stderr : String(err.stderr || '');
13513
- const output = `${stdout}\n${stderr}`.trim();
13514
- const version = parseBinaryVersionOutput(output);
13515
- const status = Number.isFinite(err.status) ? err.status : null;
13516
- if (version && status === 0) {
13517
- return {
13518
- installed: true,
13519
- bin: binName,
13520
- version,
13521
- path: resolveCommandPath(binName),
13522
- error: ''
13523
- };
13524
- }
13525
- if (version) {
13526
- lastError = status !== null
13527
- ? `${binName} exited with ${status}: ${version}`
13528
- : `${binName} failed: ${version}`;
13501
+ const version = parseBinaryVersionOutput(`${error.stdout || ''}\n${error.stderr || ''}`);
13502
+ if (!isWindows && Number.isInteger(error.code)) {
13503
+ // The executable exists even if its version flag exits nonzero.
13504
+ output = version;
13505
+ } else {
13506
+ if (version) {
13507
+ lastError = Number.isInteger(error.code)
13508
+ ? `${binName} exited with ${error.code}: ${version}`
13509
+ : `${binName} failed: ${version}`;
13510
+ } else if (error.message && !/ENOENT/i.test(error.message)) {
13511
+ lastError = error.message;
13512
+ }
13529
13513
  continue;
13530
13514
  }
13531
- const message = err && err.message ? String(err.message) : '';
13532
- if (message && !/ENOENT/i.test(message)) {
13533
- lastError = message;
13534
- }
13535
13515
  }
13516
+ return {
13517
+ installed: true,
13518
+ bin: binName,
13519
+ version: parseBinaryVersionOutput(output) || 'unknown',
13520
+ path: await locateInstallBinary(binName),
13521
+ error: ''
13522
+ };
13536
13523
  }
13537
13524
 
13538
13525
  return {
@@ -13582,13 +13569,15 @@ function resolveInstallCommandsByPackageManager(packageManager) {
13582
13569
  };
13583
13570
  }
13584
13571
 
13585
- function buildInstallStatusReport() {
13586
- const packageManager = detectPreferredPackageManager();
13587
- const targetReports = CLI_INSTALL_TARGETS.map((target) => {
13572
+ async function buildInstallStatusReport() {
13573
+ // Version probes must not block the server while startup reads its configuration.
13574
+ const packageManager = await detectPreferredPackageManager();
13575
+ const targetReports = [];
13576
+ for (const target of CLI_INSTALL_TARGETS) {
13588
13577
  let hit = null;
13589
13578
  let lastError = '';
13590
13579
  for (const binName of target.bins) {
13591
- const probe = probeCliBinary(binName);
13580
+ const probe = await probeCliBinary(binName);
13592
13581
  if (probe.installed) {
13593
13582
  hit = probe;
13594
13583
  break;
@@ -13597,7 +13586,7 @@ function buildInstallStatusReport() {
13597
13586
  lastError = probe.error;
13598
13587
  }
13599
13588
  }
13600
- return {
13589
+ targetReports.push({
13601
13590
  id: target.id,
13602
13591
  name: target.name,
13603
13592
  packageName: target.packageName,
@@ -13606,8 +13595,8 @@ function buildInstallStatusReport() {
13606
13595
  version: hit ? hit.version : '',
13607
13596
  commandPath: hit ? hit.path : '',
13608
13597
  error: hit ? '' : lastError
13609
- };
13610
- });
13598
+ });
13599
+ }
13611
13600
 
13612
13601
  const commandSpec = resolveInstallCommandsByPackageManager(packageManager);
13613
13602
  return {
@@ -14558,7 +14547,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14558
14547
  sendJson(405, { error: 'Method Not Allowed' });
14559
14548
  return;
14560
14549
  }
14561
- let body = '';
14550
+ const bodyChunks = [];
14562
14551
  let bodySize = 0;
14563
14552
  let bodyTooLarge = false;
14564
14553
  req.on('data', chunk => {
@@ -14572,13 +14561,13 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14572
14561
  req.destroy();
14573
14562
  return;
14574
14563
  }
14575
- body += chunk;
14564
+ bodyChunks.push(chunk);
14576
14565
  });
14577
14566
  req.on('end', async () => {
14578
14567
  if (bodyTooLarge) return;
14579
14568
  let leaveToolConfigWriteGuard = null;
14580
14569
  try {
14581
- const { action, params } = JSON.parse(body || '{}');
14570
+ const { action, params } = JSON.parse(Buffer.concat(bodyChunks, bodySize).toString('utf8') || '{}');
14582
14571
  leaveToolConfigWriteGuard = typeof enterToolConfigWriteGuard === 'function'
14583
14572
  ? enterToolConfigWriteGuard()
14584
14573
  : () => {};
@@ -14616,6 +14605,14 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14616
14605
  case 'get-tool-config-permissions':
14617
14606
  result = { permissions: readToolConfigPermissions() };
14618
14607
  break;
14608
+ case 'knowledge-list':
14609
+ case 'knowledge-get':
14610
+ case 'knowledge-create':
14611
+ case 'knowledge-update': {
14612
+ const { status, payload } = sharedKnowledge(action, params);
14613
+ sendJson(status, payload);
14614
+ return;
14615
+ }
14619
14616
  case 'get-web-ui-preferences':
14620
14617
  result = { preferences: readWebUiPreferences() };
14621
14618
  break;
@@ -14708,7 +14705,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14708
14705
  break;
14709
14706
  }
14710
14707
  case 'install-status':
14711
- result = buildInstallStatusReport();
14708
+ result = await buildInstallStatusReport();
14712
14709
  break;
14713
14710
  case 'version-status': {
14714
14711
  const currentVersion = (() => {
@@ -15312,6 +15309,9 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15312
15309
  case 'model-test-catalog':
15313
15310
  result = { catalogs: modelTests.catalog() };
15314
15311
  break;
15312
+ case 'model-test-discover':
15313
+ result = await modelTests.discover(params || {});
15314
+ break;
15315
15315
  case 'model-test-run':
15316
15316
  result = await modelTests.run(params || {});
15317
15317
  break;
@@ -15565,6 +15565,20 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15565
15565
  fileName: path.basename(legacyFilePath),
15566
15566
  deleteAfterDownload: false
15567
15567
  });
15568
+ } else if (requestPath === '/res/geist/index.css' || /^\/res\/geist\/files\/geist-(?:latin|latin-ext|vietnamese|cyrillic|cyrillic-ext)-wght-normal\.woff2$/.test(requestPath)) {
15569
+ const asset = requestPath.slice('/res/geist/'.length);
15570
+ try {
15571
+ const fontPath = require.resolve(`@fontsource-variable/geist/${asset}`);
15572
+ const mime = asset === 'index.css' ? 'text/css; charset=utf-8' : 'font/woff2';
15573
+ const stream = fs.createReadStream(fontPath);
15574
+ stream.once('error', error => writeWebUiAssetError(res, requestPath, error));
15575
+ stream.once('open', () => {
15576
+ res.writeHead(200, { 'Content-Type': mime, 'Cache-Control': 'no-store, max-age=0' });
15577
+ stream.pipe(res);
15578
+ });
15579
+ } catch (error) {
15580
+ writeWebUiAssetError(res, requestPath, error);
15581
+ }
15568
15582
  } else if (requestPath.startsWith('/res/')) {
15569
15583
  const normalized = path.normalize(requestPath.slice('/res/'.length)).replace(/^([\\.\\/])+/, '');
15570
15584
  const filePath = path.join(assetsDir, normalized);
@@ -15585,7 +15599,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15585
15599
  ? 'text/html; charset=utf-8'
15586
15600
  : ext === '.json'
15587
15601
  ? 'application/json; charset=utf-8'
15588
- : 'application/octet-stream';
15602
+ : ext === '.svg' ? 'image/svg+xml' : 'application/octet-stream';
15589
15603
  res.writeHead(200, {
15590
15604
  'Content-Type': mime,
15591
15605
  'Cache-Control': 'no-store, max-age=0'
package/lib/model-test.js CHANGED
@@ -1,3 +1,4 @@
1
+ const { createHash, randomUUID } = require('crypto');
1
2
  const http = require('http');
2
3
  const https = require('https');
3
4
  const { modelTestClientHeaders } = require('./model-test-client');
@@ -6,6 +7,10 @@ const { buildApiProbeUrlCandidates, extractModelResponseText } = require('./cli-
6
7
  const MAX_PROMPT_LENGTH = 8000;
7
8
  const MAX_RESPONSE_BYTES = 256 * 1024;
8
9
  const MAX_OUTPUT_TOKENS = 2048;
10
+ const MAX_CATALOG_BYTES = 8 * 1024 * 1024;
11
+ const MAX_CATALOG_PAGES = 1000;
12
+ const MAX_CATALOG_SNAPSHOTS = 32;
13
+ const CATALOG_TIMEOUT_MS = 20000;
9
14
  const SUPPORTED_APIS = new Set(['responses', 'chat_completions', 'completions', 'anthropic-messages']);
10
15
  const PI_NON_STANDARD_PROVIDERS = new Set(['cerebras', 'xai', 'zai', 'opencode']);
11
16
 
@@ -14,14 +19,7 @@ function buildTestRequest(provider, model, prompt) {
14
19
  if (!SUPPORTED_APIS.has(api)) throw new Error('此配置的接口暂不支持真实测试');
15
20
  const paths = { responses: 'responses', chat_completions: 'chat/completions', completions: 'completions', 'anthropic-messages': 'messages' };
16
21
  const url = buildApiProbeUrlCandidates(provider.baseUrl, paths[api])[0];
17
- const key = (provider.apiKey || '').replace(/^Bearer\s+/i, '');
18
- const authentication = api === 'anthropic-messages'
19
- ? { 'anthropic-version': '2023-06-01', ...(key ? { 'x-api-key': key } : {}) }
20
- : key ? { authorization: `Bearer ${key}` } : {};
21
- const headers = Object.fromEntries([
22
- ...Object.entries(provider.clientHeaders || {}), ...Object.entries(authentication),
23
- ...Object.entries(provider.headers || {})
24
- ].map(([name, value]) => [name.toLowerCase(), value]));
22
+ const headers = buildTestHeaders(provider);
25
23
  const maxTokens = Number.isFinite(provider.maxTokens) && provider.maxTokens > 0
26
24
  ? Math.min(provider.maxTokens, MAX_OUTPUT_TOKENS) : MAX_OUTPUT_TOKENS;
27
25
  let body;
@@ -51,22 +49,33 @@ function buildTestRequest(provider, model, prompt) {
51
49
  return { url, headers, body };
52
50
  }
53
51
 
52
+ function buildTestHeaders(provider) {
53
+ const key = (provider.apiKey || '').replace(/^Bearer\s+/i, '');
54
+ const authentication = provider.api === 'anthropic-messages'
55
+ ? { 'anthropic-version': '2023-06-01', ...(key ? { 'x-api-key': key } : {}) }
56
+ : key ? { authorization: `Bearer ${key}` } : {};
57
+ return Object.fromEntries([
58
+ ...Object.entries(provider.clientHeaders || {}), ...Object.entries(authentication),
59
+ ...Object.entries(provider.headers || {})
60
+ ].map(([name, value]) => [name.toLowerCase(), value]));
61
+ }
62
+
54
63
  function requestModel({ url, headers, body }, { timeoutMs = 0, maxBytes = MAX_RESPONSE_BYTES } = {}) {
55
64
  return new Promise((resolve, reject) => {
56
65
  const parsed = new URL(url);
57
66
  if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('供应商地址必须使用 HTTP 或 HTTPS');
58
- const payload = JSON.stringify(body);
67
+ const payload = body === undefined ? undefined : JSON.stringify(body);
59
68
  const transport = parsed.protocol === 'https:' ? https : http;
60
- // A single request, no probe fallback or retry: a test can incur usage charges.
61
- const request = transport.request(parsed, { method: 'POST', headers: {
62
- ...headers, 'Content-Type': 'application/json', Accept: 'application/json', 'Content-Length': Buffer.byteLength(payload)
69
+ const request = transport.request(parsed, { method: payload === undefined ? 'GET' : 'POST', headers: {
70
+ ...headers, Accept: 'application/json',
71
+ ...(payload === undefined ? {} : { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) })
63
72
  } }, response => {
64
73
  const chunks = [];
65
74
  let size = 0;
66
75
  response.on('data', chunk => {
67
76
  size += chunk.length;
68
77
  if (size > maxBytes) {
69
- reject(new Error('回复超过 256 KiB,测试已停止'));
78
+ reject(new Error(`回复超过 ${body === undefined ? '8 MiB' : '256 KiB'},测试已停止`));
70
79
  response.destroy(); request.destroy(); return;
71
80
  }
72
81
  chunks.push(chunk);
@@ -87,7 +96,95 @@ function requestModel({ url, headers, body }, { timeoutMs = 0, maxBytes = MAX_RE
87
96
  });
88
97
  }
89
98
 
90
- function createModelTestService({ providers, request = requestModel, clientHeaders = modelTestClientHeaders }) {
99
+ function readListedModels(payload) {
100
+ const items = Array.isArray(payload) ? payload : payload.data ?? payload.models;
101
+ if (!Array.isArray(items)) throw new Error('上游未返回有效模型目录');
102
+ return items.map(item => {
103
+ const id = typeof item === 'string' ? item : item?.id ?? item?.model ?? item?.name;
104
+ if (typeof id !== 'string' || !id.trim()) throw new Error('上游模型目录缺少模型 ID');
105
+ return id.trim();
106
+ });
107
+ }
108
+
109
+ function nextCatalogPage(payload, currentUrl, ids) {
110
+ const next = payload.next ?? payload.links?.next;
111
+ if (next != null && typeof next !== 'string') throw new Error('上游返回无效的模型目录分页地址');
112
+ if (next) {
113
+ const url = new URL(next, currentUrl);
114
+ if (url.origin !== currentUrl.origin || url.pathname !== currentUrl.pathname || url.username || url.password) {
115
+ throw new Error('上游目录分页地址超出当前供应商模型目录');
116
+ }
117
+ url.hash = '';
118
+ return url;
119
+ }
120
+ if (!payload.has_more) return null;
121
+ const cursor = payload.last_id ?? ids.at(-1);
122
+ if (typeof cursor !== 'string' || !cursor) throw new Error('上游模型目录缺少分页游标');
123
+ const url = new URL(currentUrl);
124
+ url.searchParams.set('after', cursor);
125
+ return url;
126
+ }
127
+
128
+ async function discoverProviderModels(provider, request) {
129
+ const baseUrl = new URL(provider.baseUrl);
130
+ if (!['http:', 'https:'].includes(baseUrl.protocol)) throw new Error('供应商地址必须使用 HTTP 或 HTTPS');
131
+ const urls = /\/models\/?$/.test(baseUrl.pathname) ? [baseUrl.href]
132
+ : buildApiProbeUrlCandidates(baseUrl.origin + baseUrl.pathname, 'models');
133
+ const headers = buildTestHeaders(provider);
134
+ const deadline = Date.now() + CATALOG_TIMEOUT_MS;
135
+ for (const candidate of urls) {
136
+ let url = new URL(candidate);
137
+ url.search = baseUrl.search;
138
+ url.hash = '';
139
+ const models = new Set();
140
+ const visited = new Set();
141
+ let bytesRead = 0;
142
+ do {
143
+ if (visited.has(url.href) || visited.size >= MAX_CATALOG_PAGES) throw new Error('上游模型目录分页循环或超出上限');
144
+ visited.add(url.href);
145
+ const timeoutMs = deadline - Date.now();
146
+ if (timeoutMs <= 0) throw new Error('读取上游模型目录超时');
147
+ const result = await request({ url: url.href, headers }, { timeoutMs, maxBytes: MAX_CATALOG_BYTES - bytesRead });
148
+ bytesRead += Buffer.byteLength(result.body);
149
+ if (visited.size === 1 && [404, 405, 501].includes(result.status)) break;
150
+ if (result.status !== 200) throw new Error(`读取上游模型目录失败:HTTP ${result.status}`);
151
+ let payload;
152
+ try { payload = JSON.parse(result.body); } catch (_) { throw new Error('上游未返回有效模型目录'); }
153
+ if (!payload || payload.error) throw new Error('上游未返回有效模型目录');
154
+ const ids = readListedModels(payload);
155
+ for (const id of ids) models.add(id);
156
+ url = nextCatalogPage(payload, url, ids);
157
+ } while (url);
158
+ if (!url) return models;
159
+ }
160
+ throw new Error('供应商未开放模型目录');
161
+ }
162
+
163
+ function providerFingerprint(provider) {
164
+ return createHash('sha256').update(JSON.stringify(provider)).digest('hex');
165
+ }
166
+
167
+ function createModelTestService({ providers, request = requestModel, listRequest = requestModel, clientHeaders = modelTestClientHeaders }) {
168
+ const snapshots = new Map();
169
+ function resolveProvider(target, name) {
170
+ if (!['codex', 'pi'].includes(target)) throw new Error('测试仅支持 Codex 和 Pi');
171
+ const provider = providers(target).find(entry => entry.name === name);
172
+ if (!provider) throw new Error('请选择已有供应商与模型,刷新后重试');
173
+ if (provider.error) throw new Error(provider.error);
174
+ return provider;
175
+ }
176
+ async function discover({ target, provider: name } = {}) {
177
+ try {
178
+ const provider = resolveProvider(target, name);
179
+ if (!provider.baseUrl) throw new Error('供应商未配置模型目录地址');
180
+ const models = await discoverProviderModels({ ...provider, clientHeaders: clientHeaders(target, provider.api) }, listRequest);
181
+ const catalogId = randomUUID();
182
+ // Bind the allowlist to the selected configuration. A changed provider must be rediscovered.
183
+ snapshots.set(catalogId, { target, name, fingerprint: providerFingerprint(provider), models });
184
+ if (snapshots.size > MAX_CATALOG_SNAPSHOTS) snapshots.delete(snapshots.keys().next().value);
185
+ return { models: [...models], catalogId };
186
+ } catch (error) { return { error: error.message }; }
187
+ }
91
188
  function catalog() {
92
189
  return Object.fromEntries(['codex', 'pi'].map(target => [target, providers(target).map(provider => ({
93
190
  name: provider.name, models: provider.models, supported: SUPPORTED_APIS.has(provider.api)
@@ -98,13 +195,21 @@ function createModelTestService({ providers, request = requestModel, clientHeade
98
195
  const identity = { target: params.target, provider: params.provider, model: params.model };
99
196
  const elapsed = () => Date.now() - started;
100
197
  try {
101
- const { target, provider: name, model, prompt } = params;
102
- if (!['codex', 'pi'].includes(target)) throw new Error('测试仅支持 Codex 和 Pi');
198
+ const { target, provider: name, model, prompt, catalogId } = params;
103
199
  if (typeof prompt !== 'string' || !prompt.trim() || prompt.length > MAX_PROMPT_LENGTH) throw new Error('输入 1–8000 字符的测试内容');
104
- const provider = providers(target).find(entry => entry.name === name);
105
- if (!provider || !provider.models.includes(model)) throw new Error('请选择已有供应商与模型,刷新后重试');
106
- if (provider.error) throw new Error(provider.error);
107
- const selected = { ...provider, ...provider.modelOptions?.[model], target };
200
+ const provider = resolveProvider(target, name);
201
+ if (catalogId !== undefined) {
202
+ const snapshot = snapshots.get(catalogId);
203
+ if (snapshot?.target !== target || snapshot.name !== name || !snapshot.models.has(model)
204
+ || snapshot.fingerprint !== providerFingerprint(provider)) throw new Error('模型目录已失效,请重新读取供应商目录');
205
+ // Keep active batches in the bounded cache, without persisting any results.
206
+ snapshots.delete(catalogId);
207
+ snapshots.set(catalogId, snapshot);
208
+ } else if (!provider.models.includes(model)) throw new Error('请选择已有供应商与模型,刷新后重试');
209
+ const overrides = provider.modelOptions && Object.hasOwn(provider.modelOptions, model) ? provider.modelOptions[model] : {};
210
+ const selected = { ...provider, ...overrides, target };
211
+ // The batch belongs to the endpoint that advertised these IDs, not a saved model’s alternate endpoint.
212
+ if (catalogId !== undefined) selected.baseUrl = provider.baseUrl;
108
213
  selected.clientHeaders = clientHeaders(target, selected.api);
109
214
  const result = await request(buildTestRequest(selected, model, prompt.trim()));
110
215
  if (result.status < 200 || result.status >= 300) return { ...identity, ok: false, status: result.status, durationMs: elapsed(), error: `HTTP ${result.status}` };
@@ -120,7 +225,7 @@ function createModelTestService({ providers, request = requestModel, clientHeade
120
225
  return { ...identity, ok: false, durationMs: elapsed(), error: error.message };
121
226
  }
122
227
  }
123
- return { catalog, run };
228
+ return { catalog, discover, run };
124
229
  }
125
230
 
126
231
  module.exports = { createModelTestService, buildTestRequest, requestModel };