locale-detect.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * User-language detection for localizing user-facing daemon output.
  3. *
  4. * # Why this exists
  5. *
  6. * Multiple daemon subsystems generate user-visible strings without going through an LLM (permission
  7. * decision reasons, team-plan engine notifications, etc.). Hardcoding English biases the UX for
  8. * English speakers; hardcoding Chinese biases the other way. This helper inspects recent user
  9. * messages and returns a coarse locale hint that callers can use to pick a localized template.
  10. *
  11. * # Scope
  12. *
  13. * Coarse classification only — `zh` (Chinese), `en` (English-like), or `unknown` (insufficient
  14. * signal). Callers must default to English when the hint is `unknown` to preserve backward
  15. * compatibility.
  16. *
  17. * # Heuristic
  18. *
  19. * Count CJK Han characters across the latest user messages. If the Han ratio is high enough (>= 20%
  20. * of non-whitespace characters), classify as `zh`. Otherwise classify as `en` when at least one
  21. * Latin letter is present, and `unknown` when there is no actionable signal (empty/only
  22. * symbols/numbers).
  23. *
  24. * The threshold is intentionally low — even a single Chinese instruction meaning "add Chinese
  25. * support to the feature above" wins over an English-heavy conversation, because the most recent
  26. * user instruction reflects current intent better than the long tail of prior turns.
  27. *
  28. * The classifier is **not** language detection in the linguistic sense — it is a one-bit signal:
  29. * "produce the Chinese template or the English template?". Treat any other language as `unknown`.
  30. */
  31. import type { AgentMessageProtocol } from '@mavis/agent-core/protocol/agent-message';
  32. /** Coarse user-language hint for picking localized templates. */
  33. export type UserLocaleHint = 'zh' | 'en' | 'unknown';
  34. /** Han (CJK Unified Ideographs) and Han-extension blocks (global, for ratio scan). */
  35. // eslint-disable-next-line no-misleading-character-class -- intentional Unicode ranges
  36. const HAN_REGEX_GLOBAL = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\u{20000}-\u{2ffff}]/gu;
  37. const LATIN_LETTER_REGEX = /[A-Za-z]/;
  38. /** Han-character ratio threshold for classifying as `zh`. */
  39. const HAN_RATIO_THRESHOLD = 0.2;
  40. /**
  41. * Detect coarse user language from a single string.
  42. *
  43. * Returns `unknown` for empty input or input that is entirely whitespace /
  44. * symbols / numbers.
  45. */
  46. export function detectTextLocale(text: string): UserLocaleHint {
  47. if (typeof text !== 'string') return 'unknown';
  48. const trimmed = text.trim();
  49. if (trimmed.length === 0) return 'unknown';
  50. // Strip whitespace before counting so the ratio reflects actual content.
  51. const compact = trimmed.replace(/\s+/g, '');
  52. if (compact.length === 0) return 'unknown';
  53. const hanMatches = compact.match(HAN_REGEX_GLOBAL);
  54. const hanCount = hanMatches ? hanMatches.length : 0;
  55. const hanRatio = hanCount / compact.length;
  56. if (hanRatio >= HAN_RATIO_THRESHOLD) return 'zh';
  57. if (LATIN_LETTER_REGEX.test(compact)) return 'en';
  58. return 'unknown';
  59. }
  60. /**
  61. * Detect coarse user language from a list of recent user messages.
  62. *
  63. * Strategy: scan the most-recent messages first; the first message that
  64. * yields a non-`unknown` verdict wins. This privileges the latest user
  65. * instruction over earlier turns.
  66. *
  67. * `messages` should contain only USER messages (or messages where the
  68. * `role` field is undefined and `msg_content` is treated as raw user
  69. * input). Callers should already filter assistant/tool messages so they
  70. * do not pollute the heuristic.
  71. *
  72. * Returns `unknown` when no message provides a usable signal.
  73. */
  74. export function detectMessagesLocale(
  75. messages: ReadonlyArray<AgentMessageProtocol> | undefined,
  76. ): UserLocaleHint {
  77. if (!messages || messages.length === 0) return 'unknown';
  78. // Iterate newest-first. Callers typically pass messages in
  79. // recency order; we explicitly reverse to handle either input
  80. // direction (oldest-first DB rows OR newest-first peek output).
  81. // Cheaper: walk both ends and pick the most-recent non-empty one.
  82. // We accept the simplicity of reversing here — message context is
  83. // bounded to <10 entries per classifier call.
  84. for (let i = messages.length - 1; i >= 0; i--) {
  85. const m = messages[i];
  86. if (!m) continue;
  87. const content = m.msg_content;
  88. if (!content) continue;
  89. const verdict = detectTextLocale(content);
  90. if (verdict !== 'unknown') return verdict;
  91. }
  92. return 'unknown';
  93. }