All files / src/components/chat/RichMarkdown processCitations.ts

100% Statements 24/24
83.33% Branches 5/6
100% Functions 11/11
100% Lines 22/22

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                                          24x 24x             96x             24x     24x 23x     24x       346x       346x 346x 5x 5x 5x   346x   386x     2x 4x     5x 5x         21x 35x   21x          
// ─── Citation pre-processor ───────────────────────────────────────────────────
// Agents emit numbered inline citations like "…15°C [1]", resolved in a closing
// "Sources" section.  Convert bare [n] markers into links to #cite-n so the `a`
// component override in RichMarkdown renders them as superscript citation chips.
//
// Some models (gpt-oss) write the marker in CJK brackets — 【1】, [1], 〔1〕 —
// or with fullwidth digits ([1]). Those are the same citation, and become
// the same ASCII link, [1](#cite-1); svc-ai normalises the stored answer the
// same way (`source_ledger.normalise_citation_markers`), but the streamed
// tokens are drawn as written. Any other 【…】 text is left as it is: it may be
// a heading or a label in Chinese or Japanese prose.
//
// Guard rails:
//   • only transforms outside fenced code blocks and inline code spans
//   • (?<![\w\]]) skips array indexing ("arr[0]") and reference links ("[x][1]");
//     a CJK bracket is never an index, so its marker may follow a word
//   • (?!\() skips real markdown links ("[1](https://…)"), and (?<!\]\() a
//     link's or an image's target ("![x]([2])"), which a marker never is
//   • an unterminated ``` fence (mid-stream) swallows the rest of the text,
//     so partial code is never rewritten while streaming
 
const _DIGITS = "[0-90-9]{1,3}";
const _CITE_RE = new RegExp(
  [
    `(?<![\\w\\]])(?<!\\]\\()\\[(${_DIGITS})\\]`,
    `【\\s*(${_DIGITS})\\s*】`,
    `[\\s*(${_DIGITS})\\s*]`,
    `〔\\s*(${_DIGITS})\\s*〕`,
  ]
    .map((form) => `${form}(?!\\()`)
    .join("|"),
  "g",
);
 
/** A pipeline id in CJK brackets (gpt-oss's 【S1】): written as svc-ai stores
 *  it, [S1], so the streamed answer reads as the stored one. */
const _WIDE_SID_RE = /[【[〔]\s*[SS]([0-90-9]{1,3})\s*[】]〕]/g;
 
/** "12" → "12": fullwidth digits sit 0xFEE0 above their ASCII ones. */
const asciiDigits = (n: string): string =>
  n.replace(/[0-9]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 0xfee0));
 
/** A source id as a model cites it, alone or grouped: [S3], [S1, S3]. */
const _SID_GROUP_RE = /(?<!\]\()\[\s*(S\d{1,3}(?:\s*[,;]\s*S?\d{1,3})*)\s*\](?!\()/gi;
 
export function processCitations(text: string): string {
  // Capturing split → odd indices are code segments, left untouched.
  const segments = text.split(/(```[\s\S]*?(?:```|$)|`[^`\n]*`)/);
  // A source id is numbered by first use, as svc-ai numbers the delivered
  // answer (``answer_sources.finalise``): an answer still streaming cites
  // [S7], and its preview reads [1] as the stored answer will.
  const order = new Map<string, number>();
  const numberOf = (sid: string): number => {
    const key = sid.toUpperCase();
    if (!order.has(key)) order.set(key, order.size + 1);
    return order.get(key)!;
  };
  return segments
    .map((seg, i) =>
      i % 2 === 1
        ? seg
        : seg
            .replace(_WIDE_SID_RE, (_m, n: string) => `[S${asciiDigits(n)}]`)
            .replace(_SID_GROUP_RE, (_m, group: string) =>
              (group.match(/\d{1,3}/g) ?? [])
                .map((n) => {
                  const m = numberOf(`S${n}`);
                  return `[${m}](#cite-${m})`;
                })
                .join(" "),
            )
            .replace(_CITE_RE, (_m, ...groups: unknown[]) => {
              const n = asciiDigits(
                groups.slice(0, 4).find((g): g is string => typeof g === "string")!,
              );
              return `[${n}](#cite-${n})`;
            }),
    )
    .join("");
}