All files / src/util citations.ts

100% Statements 12/12
100% Branches 14/14
100% Functions 4/4
100% Lines 9/9

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                              8x     24x                                   58x 58x 10x 10x 8x 8x 8x                        
import { Citation, isCitationKind } from "@/objects/Model";
 
/**
 * A chat turn's citations after one `citations` frame.
 *
 * svc-ai streams every passage as it is retrieved, before any answer is
 * written; once the answer is, svc-core sends the ones it actually cites as
 * a `final` frame (svc-ai `source_ledger.cited_citations`). That list
 * replaces the streamed one, so a passage the answer never used — the user
 * guide, for a question about today's news — is not shown as its source.
 */
export function nextCitations(
  accumulated: Citation[],
  frame: { citations: Citation[]; final?: boolean },
): Citation[] {
  return frame.final ? [...frame.citations] : [...accumulated, ...frame.citations];
}
 
const text = (value: unknown): string => (typeof value === "string" ? value : "");
 
/**
 * The sources an answer cites, as svc-core stored them on its message
 * (`meta.cited_sources`): what the chat showed when the answer was written,
 * on any device and after any reload.
 *
 * `undefined` when the message has no such key — a turn stored before
 * October 2026, or a blocked one — so the caller can fall back to what it
 * has; `[]` when the answer was stored citing nothing, which is an answer,
 * not a gap. The projection leaves out what the card never reads (the
 * passage's text, its score), and an entry may lack a key the card does
 * read, so each is made safe to draw: no entry without a string `source`
 * and `title`, a numeric `index`, and a `kind` only when it is one.
 */
export function storedCitations(
  meta: { cited_sources?: unknown } | null | undefined,
): Citation[] | undefined {
  const stored = meta?.cited_sources;
  if (!Array.isArray(stored)) return undefined;
  return stored.flatMap((entry: unknown, i): Citation[] => {
    if (!entry || typeof entry !== "object") return [];
    const raw = entry as Record<string, unknown>;
    const { kind, ...rest } = raw;
    return [
      {
        ...rest,
        index: typeof raw.index === "number" ? raw.index : i + 1,
        tool: text(raw.tool),
        source: text(raw.source),
        title: text(raw.title),
        ...(isCitationKind(kind) ? { kind } : {}),
      } as Citation,
    ];
  });
}