File size: 2,183 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
/** Formatting helpers for model-list terminal tables. */
import { truncateToVisibleWidth, visibleWidth } from "../../../packages/terminal-core/src/ansi.js";
import { sanitizeTerminalText } from "../../../packages/terminal-core/src/safe-text.js";
import { isRich as isRichTerminal, theme } from "../../../packages/terminal-core/src/theme.js";

const TRUNCATED_SUFFIX = "...";

/** Formats token counts as compact decimal-K labels. */
export const formatTokenK = (value?: number | null) => {
  if (!value || !Number.isFinite(value)) {
    return "-";
  }
  // Provider context windows use decimal K, so 200000 must stay "200k".
  if (value < 1000) {
    return `${Math.round(value)}`;
  }
  return `${Math.round(value / 1000)}k`;
};

/** Enables rich formatting only for non-machine-readable output. */
export const isRich = (opts?: { json?: boolean; plain?: boolean }) =>
  isRichTerminal() && !opts?.json && !opts?.plain;

/** Pads a table cell to a fixed terminal visible width. */
export const padTerminalCell = (value: string, size: number) => {
  const remaining = size - visibleWidth(value);
  return remaining > 0 ? `${value}${" ".repeat(remaining)}` : value;
};

/** Applies terminal color based on a model-list tag. */
export const formatTag = (tag: string) => {
  if (tag === "default") {
    return theme.success(tag);
  }
  if (tag === "image") {
    return theme.accentBright(tag);
  }
  if (tag === "configured") {
    return theme.accent(tag);
  }
  if (tag === "missing") {
    return theme.error(tag);
  }
  if (tag.startsWith("fallback#") || tag.startsWith("img-fallback#")) {
    return theme.warn(tag);
  }
  if (tag.startsWith("alias:")) {
    return theme.accentDim(tag);
  }
  return theme.muted(tag);
};

/** Truncates model-list cells to terminal visible width with an ASCII ellipsis. */
export const truncate = (value: string, max: number) => {
  const sanitized = sanitizeTerminalText(value);
  if (visibleWidth(sanitized) <= max) {
    return sanitized;
  }
  if (max <= TRUNCATED_SUFFIX.length) {
    return truncateToVisibleWidth(sanitized, max);
  }
  return `${truncateToVisibleWidth(sanitized, max - TRUNCATED_SUFFIX.length)}${TRUNCATED_SUFFIX}`;
};