model-selection-key.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import type { ModelSelectionGhostReason } from "./model-selection-types.js";
  2. import { decodeCustomModelValue } from "./custom-model-value.js";
  3. import type { ZCodeProvider } from "./zcode-task-types-core.js";
  4. export const NATIVE_SUPPLIER_KEY_PREFIX = "native:";
  5. export const CUSTOM_SUPPLIER_KEY_PREFIX = "custom:";
  6. export const GHOST_SUPPLIER_KEY_PREFIX = "ghost:";
  7. const TRAILING_SLASHES_RE = /\/+$/;
  8. const MAX_ENCODED_GHOST_IDENTITY_LENGTH = 160;
  9. function fnv1a32(value: string, seed = 0x811c9dc5): number {
  10. let hash = seed >>> 0;
  11. for (const char of value) {
  12. hash ^= char.codePointAt(0) ?? 0;
  13. hash = Math.imul(hash, 0x01000193);
  14. hash >>>= 0;
  15. }
  16. return hash >>> 0;
  17. }
  18. function hash12(value: string): string {
  19. const high = fnv1a32(value, 0x811c9dc5).toString(16).padStart(8, "0");
  20. const low = fnv1a32(value, 0x9e3779b1).toString(16).padStart(8, "0");
  21. return `${high}${low}`.slice(0, 12);
  22. }
  23. export function normalizeSupplierBaseUrl(baseUrl: string): string {
  24. return baseUrl.trim().replace(TRAILING_SLASHES_RE, "");
  25. }
  26. export function buildNativeSupplierKey(zcodeProvider: ZCodeProvider): string {
  27. return `${NATIVE_SUPPLIER_KEY_PREFIX}${zcodeProvider}`;
  28. }
  29. export function buildCustomSupplierKey(providerId: string): string {
  30. return `${CUSTOM_SUPPLIER_KEY_PREFIX}${providerId.trim()}`;
  31. }
  32. export function buildGhostSupplierIdentity(rawIdentity: string): string {
  33. const encodedIdentity = encodeURIComponent(rawIdentity.trim() || "unknown");
  34. if (encodedIdentity.length <= MAX_ENCODED_GHOST_IDENTITY_LENGTH) {
  35. return encodedIdentity;
  36. }
  37. // ghost identity 可能包含长 URL,直接拼 key 会放大状态串并污染日志。
  38. // 超长时退化成稳定摘要,避免 selectedSupplierKey 无限增长。
  39. return `hash=${hash12(rawIdentity)}`;
  40. }
  41. export function buildGhostSupplierKey(
  42. zcodeProvider: ZCodeProvider,
  43. reason: ModelSelectionGhostReason,
  44. rawIdentity: string,
  45. ): string {
  46. return [
  47. GHOST_SUPPLIER_KEY_PREFIX,
  48. zcodeProvider,
  49. ":",
  50. reason,
  51. ":",
  52. buildGhostSupplierIdentity(rawIdentity),
  53. ].join("");
  54. }
  55. export function resolveSupplierKeyFromModelDisplayValue(
  56. zcodeProvider: ZCodeProvider,
  57. value: string | boolean | undefined,
  58. ): string {
  59. const customModel = decodeCustomModelValue(String(value ?? ""));
  60. if (customModel?.providerId) {
  61. return buildCustomSupplierKey(customModel.providerId);
  62. }
  63. return buildNativeSupplierKey(zcodeProvider);
  64. }