All files / src/util webSearchReport.ts

98.3% Statements 58/59
93.22% Branches 55/59
100% Functions 11/11
100% Lines 49/49

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148                                29x                         29x                 29x                   29x 13x     29x         29x     9x 7x 7x 2x       5x           29x 6x 11x   10x 10x 8x 5x 5x   6x       29x 5x 5x 4x   1x   5x 3x   5x   2x 2x   5x 1x   5x     29x             29x           9x 7x 6x 2x       4x   3x     3x   1x         29x 7x 6x 6x 6x      
import type {
  SearchOutcome,
  SearchRemoval,
  SearchReport,
  SettledWeb,
} from "@/objects/WebSearch";
 
/**
 * A web search's report, and a Tools rule's settled effect, in words
 * (`objects/WebSearch.ts`). Every phrase is keyed by the vocabulary it
 * describes, and nothing here names an engine: "the search engine" is the
 * first asked, "the fallback engine" any after it — as the tool tells the
 * model.
 */
 
/** Why an engine could not answer (svc-ai's `FailureReason`). */
export const FAILURE_LABELS: Record<string, string> = {
  quota: "its usage quota is used up",
  rate_limited: "it is rate-limited",
  auth: "it refused the platform's credentials",
  refused: "it refused the request",
  timeout: "it timed out",
  network: "it could not be reached",
  unsupported: "it does not offer this kind of search",
  error: "it failed",
};
 
/** What removed a result, after its count: "2 ruled out by the
 *  workspace's rules". */
export const REMOVAL_LABELS: Record<SearchRemoval, string> = {
  safety: "removed by the safety filters",
  tool_config: "removed by the tool's configured sites",
  rules_blocked: "ruled out by the workspace's rules",
  rules_not_allowed: "outside the only sources the workspace's rules allow",
  not_requested: "outside the sites the agent asked for",
};
 
/** What a call came to, as a short label. */
export const SEARCH_OUTCOME_LABELS: Record<SearchOutcome, string> = {
  found: "Found results",
  empty: "No results",
  unavailable: "Unavailable",
  closed: "No source allowed",
  refused: "Sites not allowed",
  call_limit: "Call limit reached",
  misconfigured: "Not set up",
};
 
const plural = (n: number, one: string, many = `${one}s`): string =>
  `${n} ${n === 1 ? one : many}`;
 
/** Results the workspace's rules removed from one search. */
export const removedByRules = (report: SearchReport): number =>
  (report.removed.rules_blocked ?? 0) + (report.removed.rules_not_allowed ?? 0);
 
/** The one thing a trace's tool row should say about a search, or null
 *  when it found results and nothing narrowed them. */
export const searchBadge = (
  report: SearchReport | null | undefined,
): { label: string; warn: boolean } | null => {
  if (!report) return null;
  const byRules = removedByRules(report);
  if (report.outcome === "found") {
    return byRules > 0
      ? { label: `${byRules} left out by rules`, warn: false }
      : null;
  }
  return { label: SEARCH_OUTCOME_LABELS[report.outcome], warn: true };
};
 
/** What each engine said, as one clause: "the search engine could not
 *  answer (its usage quota is used up); the fallback engine returned no
 *  results". Empty when the first engine answered. */
export const describeEngines = (report: SearchReport): string => {
  const said = report.attempts
    .filter((a) => a.outcome !== "answered" || a.engine === "fallback")
    .map((a) => {
      const who = a.engine === "primary" ? "the search engine" : "the fallback engine";
      if (a.outcome === "answered") return `${who} returned ${plural(a.returned, "result")}`;
      if (a.outcome === "empty") return `${who} returned no results`;
      Iif (a.outcome === "skipped") return `${who} was not asked in time`;
      return `${who} could not answer (${FAILURE_LABELS[a.reason ?? "error"] ?? FAILURE_LABELS.error})`;
    });
  return Array.from(new Set(said)).join("; ");
};
 
/** One search, in a line: what came back and what was removed. */
export const describeSearch = (report: SearchReport): string => {
  const parts: string[] = [];
  if (report.outcome === "found") {
    parts.push(`Kept ${plural(report.kept, "result")} of ${report.returned}`);
  } else {
    parts.push(SEARCH_OUTCOME_LABELS[report.outcome]);
  }
  for (const [kind, n] of Object.entries(report.removed) as [SearchRemoval, number][]) {
    Eif (n) parts.push(`${n} ${REMOVAL_LABELS[kind]}`);
  }
  if (report.put_first.length) {
    // Whose sources: the workspace's rules, or CHAIN-R's for CHAINR Bot.
    const by = report.sources_set_by === "platform" ? "by CHAIN-R" : "by the rules";
    parts.push(`${report.put_first.join(", ")} put first ${by}`);
  }
  if (report.searched_as && report.searched_as !== report.search_type) {
    parts.push(`searched as a ${report.searched_as} search`);
  }
  return parts.join(" · ");
};
 
const searches = (n: number) => plural(n, "search", "searches");
 
/**
 * What a Tools rule did to the turn's searches, once settled after the run
 * (`detail[action].web`), after the line saying what the rule is (`base`):
 * whether any search met it at all.
 */
export const describeSettledWeb = (
  base: string,
  web: SettledWeb,
  action: string,
  only: boolean,
): string => {
  if (web.searches === 0) return `${base} — in force; the agent did not search the web`;
  if (web.closed) return `${base} — no web source was left to search`;
  if (action === "trusted_sources" && !only) {
    return web.put_first > 0
      ? `${base} — its sources came first`
      : `${base} — none came up in ${searches(web.searches)}`;
  }
  if (web.narrowed > 0) {
    const what =
      web.left_out > 0
        ? `left out ${plural(web.left_out, "site")}`
        : "kept the search to its sources";
    return `${base} — ${what} in ${web.narrowed} of ${searches(web.searches)}`;
  }
  return `${base} — changed none of ${searches(web.searches)}`;
};
 
/** Whether a settled Tools rule changed a search — what draws attention to
 *  an answer. Putting a source first is not narrowing. */
export const narrowedBySettledWeb = (detail: unknown): boolean => {
  if (!detail || typeof detail !== "object") return false;
  return Object.values(detail as Record<string, unknown>).some((block) => {
    const web = (block as { web?: SettledWeb } | null)?.web;
    return !!web && web.narrowed > 0;
  });
};