All files / src/util webSearchNotice.ts

97.77% Statements 44/45
82.6% Branches 57/69
100% Functions 10/10
97.43% Lines 38/39

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                                                                                        19x 62x     19x 13x 12x       1x     19x   19x     19x 11x 11x 11x 5x 4x     5x 3x   5x           6x 4x 1x         3x         11x                     19x   9x 9x           25x 24x 10x   11x 10x     10x   14x 9x 9x           5x 3x       3x               2x    
import type { WebSearchRuleEffect, WebSearchSummary } from "@/objects/WebSearch";
import { FAILURE_LABELS } from "@/util/webSearchReport";
 
/**
 * What the note under an answer says about its web searches
 * (`meta.web_search`, svc-core `web_search_summary.summarise`) — pure, so
 * the chat only draws it.
 *
 * Said only when it changes how the answer reads:
 *
 * - **closed** — the workspace's rules left no web source at all;
 * - **limited** — a Tools rule narrowed a search: which rule, the sites it
 *   allowed or ruled out, and the sites it left out — each with the change
 *   that would let the agent use one (`edit`), which the note offers to
 *   whoever may make it;
 * - **empty / unavailable** — no rule was involved: what the engines said,
 *   so nobody reads a provider's failure as a rule, and the question can
 *   be asked again.
 *
 * Nothing for a turn whose searches found what they looked for, nor for a
 * rule that only put its sources first: neither changed what the answer
 * could use.
 */
 
/** What would let the agent use a source a rule kept from it — offered as
 *  an edit of the rule, never applied for the person. */
export interface NoticeEdit {
  kind: "add_trusted" | "remove_blocked";
  domain: string;
}
 
export interface NoticeLine {
  rule_id?: string | null;
  rule?: string | null;
  text: string;
  edit?: NoticeEdit;
}
 
export type WebSearchNotice =
  | { kind: "closed" | "limited"; lines: NoticeLine[] }
  | { kind: "empty" | "unavailable"; text: string; askAgain: true };
 
/** Whether `domain` covers `host` — the host itself or a subdomain of it,
 *  as svc-core's `web_domains.covered` reads it. */
export const covers = (domain: string, host: string): boolean =>
  host === domain || host.endsWith(`.${domain}`);
 
/** A list in prose, at most `limit` named: "a, b and 2 more". */
export const named = (items: string[], limit = 3): string => {
  if (items.length <= limit) {
    return items.length > 1
      ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`
      : (items[0] ?? "");
  }
  return `${items.slice(0, limit).join(", ")} and ${items.length - limit} more`;
};
 
const quoted = (rule?: string | null) => (rule ? `“${rule}”` : "a rule");
 
const sites = (n: number) => (n === 1 ? "1 site" : `${n} sites`);
 
/** One rule's part, or null when it narrowed nothing. */
const lineOf = (effect: WebSearchRuleEffect): NoticeLine | null => {
  const base = { rule_id: effect.rule_id, rule: effect.rule };
  const leftOut = effect.left_out ?? [];
  if (effect.action === "blocked_sources") {
    if (!effect.narrowed) return null;
    const what = leftOut.length ? named(leftOut) : sites(effect.left_out_count);
    // The rule's own domain that ruled the first site out: what removing
    // would let the agent use.
    const domain = leftOut.length
      ? effect.domains.find((d) => covers(d, leftOut[0]))
      : undefined;
    return {
      ...base,
      text: `Left out ${what} — ruled out by ${quoted(effect.rule)}.`,
      ...(domain ? { edit: { kind: "remove_blocked", domain } } : {}),
    };
  }
  if (!effect.only || !effect.narrowed) return null;
  if (effect.closed) {
    return {
      ...base,
      text: `${quoted(effect.rule)} allows only ${named(effect.domains)}, and no source was left to search.`,
    };
  }
  const outside = leftOut.length
    ? `; left out ${named(leftOut)}`
    : effect.left_out_count
      ? `; left out ${sites(effect.left_out_count)}`
      : "";
  return {
    ...base,
    text: `Searched only ${named(effect.domains)} — set by ${quoted(effect.rule)}${outside}.`,
    ...(leftOut.length
      ? { edit: { kind: "add_trusted", domain: leftOut[0] } }
      : {}),
  };
};
 
/** What the engines failed with, most often first: "its usage quota is
 *  used up". */
const failure = (failures: Record<string, number>): string | null => {
  const [reason] =
    Object.entries(failures).sort(([, a], [, b]) => b - a)[0] ?? [];
  return reason ? (FAILURE_LABELS[reason] ?? FAILURE_LABELS.error) : null;
};
 
export function webSearchNotice(
  summary: WebSearchSummary | null | undefined,
): WebSearchNotice | null {
  if (!summary) return null;
  if (summary.outcome === "closed" || summary.outcome === "limited") {
    const lines = summary.rules
      .map(lineOf)
      .filter((line): line is NoticeLine => line !== null);
    Iif (summary.outcome === "closed" && lines.length === 0) {
      lines.push({ text: "The workspace's rules left no web source to search." });
    }
    return lines.length ? { kind: summary.outcome, lines } : null;
  }
  if (summary.outcome === "unavailable") {
    const why = failure(summary.failures);
    return {
      kind: "unavailable",
      text: `No trust rule limited this search. The search engine was unavailable${why ? ` (${why})` : ""}.`,
      askAgain: true,
    };
  }
  if (summary.outcome === "empty") {
    const filtered =
      (summary.removed.safety ?? 0) +
      (summary.removed.tool_config ?? 0) +
      (summary.removed.not_requested ?? 0);
    return {
      kind: "empty",
      text: filtered
        ? "No trust rule limited this search. What came back was removed by the platform's safety checks or the search's own settings."
        : "No trust rule limited this search. The search engine returned no results.",
      askAgain: true,
    };
  }
  return null;
}