All files / src/capabilities ResourceGovernor.ts

100% Statements 16/16
100% Branches 6/6
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                        10x 10x 10x     10x   10x 9x 9x   1x 1x       10x 10x   10x     10x 8x     10x                 1x                  
import { EnvironmentDetector } from "./EnvironmentDetector.js";
 
/**
 * 実行環境のリソース制限を動的に調整するガバナー。
 */
export class ResourceGovernor {
  /**
   * 現在の環境に合わせて、推奨されるエンジンのオプション設定を取得します。
   */
  public static async getRecommendedOptions(
    options?: Record<string, unknown>,
  ): Promise<Record<string, unknown>> {
    const caps = await EnvironmentDetector.detect();
    const security = await EnvironmentDetector.getSecurityStatus();
    const recommended = { ...options };
 
    // 1. スレッド数 (Threads)
    const threads = EnvironmentDetector.getRecommendedThreads();
    // 2026: COOP/COEP が無効な場合はシングルスレッドに強制フォールバック
    if (!security.canUseThreads || !caps.wasmThreads) {
      recommended["Threads"] = 1;
      recommended["MultiThreaded"] = false;
    } else {
      recommended["Threads"] = threads;
      recommended["MultiThreaded"] = true;
    }
 
    // 2. ハッシュサイズ (Hash) - MB 単位
    const maxMemory = EnvironmentDetector.getRecommendedMaxMemory();
    const maxHashMB = Math.floor(maxMemory / (1024 * 1024));
    // モバイル等のメモリ制限を反映。上限 512MB 程度 (UI の滑らかさを優先)。
    recommended["Hash"] = Math.min(512, maxHashMB);
 
    // 3. その他、環境に応じた最適化
    if (!caps.wasmSimd) {
      recommended["Simd"] = false;
    }
 
    return recommended;
  }
 
  /**
   * 2026 Zenith: 省電力モード (LowPowerMode) を適用します。
   */
  public static applyLowPowerMode(
    options: Record<string, unknown>,
  ): Record<string, unknown> {
    return {
      ...options,
      Threads: 1,
      Hash: 16, // 最小限のハッシュ
      Ponder: false, // 思考中にバックグラウンドで動かさない
      SlowMover: 10, // 思考を早めに切り上げる
    };
  }
}