();
+ for (const node of positioned) {
+ const key = positionKey(node);
+ claimed.set(key, (claimed.get(key) ?? 0) + 1);
+ }
+ for (const node of positioned) {
+ const key = positionKey(node);
+ if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position;
+ }
+ return root;
+}
+
+/** The stack index of the `` an HTML parser would close, or -1 when none is in scope. */
+function openParagraph(stack: ReadonlyArray): number {
+ for (let index = stack.length - 1; index > 0; index--) {
+ const tagName = (stack[index] as Element).tagName;
+ if (tagName === "p") return index;
+ if (PARAGRAPH_SCOPE.has(tagName)) return -1;
+ }
+ return -1;
+}
+
+/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */
+function normalizeRawTables(node: Root | Element) {
+ for (const child of node.children) {
+ if (child.type === "element") normalizeRawTables(child);
+ }
+ if (node.type !== "element" || node.tagName !== "table") return;
+ const first = node.children.findIndex((child) => isElement(child, "tr"));
+ if (first < 0) return;
+ node.children = [
+ ...node.children.slice(0, first),
+ { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) },
+ ];
+}
+
+// Words leaves these raw in Markdown destinations, where micromark percent-encodes them.
+const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g;
+const normalizeUri = (value: string) =>
+ value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character));
+
+const windowsPath = (url: string) => {
+ const path = url.replace(/%5C/gi, "\\");
+ return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined;
+};
+
+const isElement = (node: unknown, tagName?: string): node is Element =>
+ (node as Element | undefined)?.type === "element" &&
+ (tagName === undefined || (node as Element).tagName === tagName);
+
+const isElementNode = (node: ElementContent): node is Element => node.type === "element";
+
+const isMarkdownImage = (node: unknown): boolean =>
+ (isElement(node, "img") && node.position !== undefined) ||
+ (isElement(node, "a") &&
+ node.position !== undefined &&
+ node.children.length === 1 &&
+ isMarkdownImage(node.children[0]));
+
+const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] };
+
+// Words' math: these elements and presentation attributes, and no links or handlers.
+const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]);
+const MATH_PROPERTIES = new Set([
+ "xmlns",
+ "width",
+ "height",
+ "viewBox",
+ "fill",
+ "fontFamily",
+ "fontSize",
+ "fontStyle",
+ "fontWeight",
+ "role",
+ "ariaLabel",
+ "x",
+ "y",
+ "dx",
+ "dy",
+ "d",
+ "transform",
+ "stroke",
+ "strokeWidth",
+ "textAnchor",
+]);
+const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/;
+
+function sanitizeMath(node: Element): Element | null {
+ if (!MATH_ELEMENTS.has(node.tagName)) return null;
+ const properties: Element["properties"] = {};
+ for (const [key, value] of Object.entries(node.properties)) {
+ if (MATH_PROPERTIES.has(key)) properties[key] = value;
+ }
+ if (typeof node.properties.style === "string") {
+ const style = node.properties.style
+ .split(";")
+ .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim()))
+ .join(";");
+ if (style) properties.style = style;
+ }
+ const children: ElementContent[] = [];
+ for (const child of node.children) {
+ if (child.type === "text") children.push(child);
+ else if (child.type === "element") {
+ const clean = sanitizeMath(child);
+ if (clean) children.push(clean);
+ }
+ }
+ return { ...node, properties, children };
+}
+
+interface Walk {
+ /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */
+ readonly render: (markdown: string, indent: number) => Root;
+ readonly source: string;
+ readonly options: WordsHastOptions;
+ readonly math: Map;
+ /** A per-render id prefix for math placeholders, which authored ids cannot share. */
+ readonly mathKey: string;
+ /** What insightSource opened each insight block with, when it opened any. */
+ readonly insightMarker: RegExp | null;
+}
+
+/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */
+function utf16Offsets(source: string): (byte: number) => number {
+ if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte;
+ const offsets: number[] = [];
+ for (let index = 0; index < source.length; index++) {
+ const code = source.codePointAt(index)!;
+ const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
+ for (let byte = 0; byte < bytes; byte++) offsets.push(index);
+ if (code >= 0x10000) index++;
+ }
+ offsets.push(source.length);
+ return (byte) => offsets[byte] ?? source.length;
+}
+
+const sourceOf = (node: Element, source: string) =>
+ node.position ? source.slice(node.position.start.offset, node.position.end.offset) : "";
+
+const textOf = (node: ElementContent): string =>
+ node.type === "text"
+ ? node.value
+ : node.type === "element"
+ ? node.children.map(textOf).join("")
+ : "";
+
+/** A directive's attributes, as strings; anything else Words would never write reads as none. */
+function directiveAttributes(node: Element): Record {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}"));
+ } catch {
+ return {};
+ }
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
+ return Object.fromEntries(
+ Object.entries(parsed).filter(
+ (entry): entry is [string, string] => typeof entry[1] === "string",
+ ),
+ );
+}
+
+/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */
+function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent {
+ const name = node.properties.dataDirective;
+ const attributes = directiveAttributes(node);
+ const asText = (): ElementContent => {
+ const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) };
+ return node.tagName === "div"
+ ? { type: "element", tagName: "p", properties: {}, children: [value] }
+ : value;
+ };
+ if (name === "codex-file-citation") {
+ const citation = resolveCodexFileCitationLink(attributes);
+ if (!citation || inLink) return asText();
+ return {
+ type: "element",
+ tagName: "a",
+ properties: { href: citation.href },
+ children: [{ type: "text", value: citation.label }],
+ ...(node.position ? { position: node.position } : {}),
+ };
+ }
+ if (name === "codex-followup") {
+ if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText();
+ return { type: "element", tagName: "span", properties: {}, children: node.children };
+ }
+ const template = resolveCodexArtifactTemplate(attributes);
+ if (!template) return asText();
+ return {
+ type: "element",
+ tagName: "div",
+ properties: {
+ dataCodexArtifactTemplate: "true",
+ dataArtifactKind: template.artifactKind,
+ dataDisplayName: template.displayName,
+ ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
+ dataSkillDirectory: template.skillDirectory,
+ dataSkillName: template.skillName,
+ },
+ children: [],
+ };
+}
+
+const INLINE_PREFIX = "t3-markdown-inline-prefix:";
+
+function stripPositions(node: ElementContent) {
+ delete node.position;
+ if (node.type === "element") node.children.forEach(stripPositions);
+}
+
+/**
+ * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but
+ * agents mean wide indentation, so code starting on the marker's line is Markdown again. True
+ * when it recovered the item, whose children it then has transformed.
+ */
+function recoverIndentedCode(
+ item: Element,
+ list: Root | Element,
+ walk: Walk,
+ inLink: boolean,
+ inCode: boolean,
+): boolean {
+ const code = item.children.find((child) => child.type === "element");
+ const start = code?.position?.start.offset;
+ const itemStart = item.position?.start.offset;
+ if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false;
+ const value = textOf(code);
+ if (!/^[\t ]/.test(value)) return false;
+ if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) {
+ return false;
+ }
+ // The trimmed first line sets where the item's content starts.
+ const indent = [.../^[\t ]*/.exec(value)![0]].reduce(
+ (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1),
+ 0,
+ );
+ // The prefix keeps block syntax at the start, such as `#`, from opening a block.
+ const source = `${INLINE_PREFIX}${value.trim()}`;
+ const recovered = walk.render(source, indent);
+ const paragraph = recovered.children.find((child) => child.type === "element");
+ const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
+ if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false;
+ first.value = first.value.slice(INLINE_PREFIX.length);
+ if (first.value === "") paragraph!.children.shift();
+ transform(recovered, { ...walk, source }, inLink, inCode);
+ transform(item, walk, inLink, inCode);
+ let blocks = recovered.children.filter(
+ (child) => !(child.type === "text" && child.value.trim() === ""),
+ ) as ElementContent[];
+ // Their positions point into `source`, not the message.
+ blocks.forEach(stripPositions);
+ let at = item.children.indexOf(code);
+ let remove = 1;
+ if (!isLooseList(list, walk.source)) {
+ // A tight item shows its text bare, as remark-rehype unwraps its paragraphs.
+ blocks = blocks.flatMap((block, index) => [
+ ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []),
+ ...(isElement(block, "p") ? block.children : [block]),
+ ]);
+ const isBlank = (node: ElementContent | undefined) =>
+ node?.type === "text" && node.value.trim() === "";
+ if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2];
+ if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++;
+ }
+ item.children.splice(at, remove, ...blocks);
+ return true;
+}
+
+/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */
+function isLooseList(list: Root | Element, source: string): boolean {
+ const items = (list.children as ElementContent[]).filter((child): child is Element =>
+ isElement(child, "li"),
+ );
+ return items.some(
+ (item, index) =>
+ item.children.some((child) => isElement(child, "p")) ||
+ (index > 0 &&
+ /\n[ \t>]*\n/.test(
+ source.slice(
+ items[index - 1]!.position?.end.offset ?? 0,
+ item.position?.start.offset ?? 0,
+ ),
+ )),
+ );
+}
+
+const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y;
+
+function keepListNumbers(list: Element, source: string) {
+ let expected = Number(list.properties.start ?? 1);
+ for (const item of list.children) {
+ if (!isElement(item, "li")) continue;
+ const offset = item.position?.start.offset;
+ WRITTEN_NUMBER.lastIndex = offset ?? 0;
+ const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1];
+ const value = digits === undefined ? expected : Number(digits);
+ if (value !== expected) item.properties.value = String(value);
+ expected = value + 1;
+ }
+}
+
+/** What the chat's remark plugins add that Words does not. */
+const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({
+ type: "element",
+ tagName: "a",
+ properties: { href, ...properties },
+ children: [{ type: "text", value: label }],
+});
+
+/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */
+function linkText(value: string, walk: Walk): ElementContent[] | null {
+ let parts: ElementContent[] = [];
+ let offset = 0;
+ for (const { index, path } of absoluteFilePathMatches(value)) {
+ if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) });
+ parts.push(link(path, path));
+ offset = index + path.length;
+ }
+ if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) });
+ const autolinks = walk.options.extensions.changeRequest?.autolinks;
+ if (autolinks) {
+ parts = parts.flatMap((part) => {
+ if (part.type !== "text") return [part];
+ const found = autolinks(part.value);
+ if (found.length === 0) return [part];
+ const linked: ElementContent[] = [];
+ let start = 0;
+ for (const reference of found) {
+ if (start < reference.index) {
+ linked.push({ type: "text", value: part.value.slice(start, reference.index) });
+ }
+ linked.push(
+ link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }),
+ );
+ start = reference.index + reference.text.length;
+ }
+ if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) });
+ return linked;
+ });
+ }
+ return parts.length === 1 && parts[0]!.type === "text" ? null : parts;
+}
+
+function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) {
+ const children = node.children as ElementContent[];
+ for (let index = 0; index < children.length; index++) {
+ const child = children[index]!;
+ if (child.type === "text") {
+ if (inCode) continue;
+ if (walk.options.extensions.githubEmoji && child.value.includes(":")) {
+ child.value = expandGithubEmojiAliases(child.value);
+ }
+ if (inLink) continue;
+ const parts = linkText(child.value, walk);
+ if (!parts) continue;
+ children.splice(index, 1, ...parts);
+ index += parts.length - 1;
+ continue;
+ }
+ if (child.type !== "element") continue;
+ // Words gives what it generates a source position; raw HTML that copies its attributes has none.
+ if (child.properties.dataDirective !== undefined && child.position) {
+ children[index] = codexDirective(child, walk, inLink);
+ index--;
+ continue;
+ }
+ const { tagName, properties: props } = child;
+ if (tagName === "svg") {
+ // Sanitizing drops SVG, so math waits under a placeholder until after it.
+ const clean = walk.options.math && child.position ? sanitizeMath(child) : null;
+ if (clean) {
+ const key = `${walk.mathKey}-${walk.math.size}`;
+ walk.math.set(key, clean);
+ children[index] = {
+ type: "element",
+ tagName: "span",
+ properties: { id: key },
+ children: [],
+ };
+ }
+ continue;
+ }
+ if (tagName === "a" && props.dataFootnoteRef !== undefined) {
+ // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again.
+ props.href = `#user-content-${String(props.href).slice(1)}`;
+ props.id = `user-content-${String(props.id)}`;
+ props.ariaDescribedBy = ["footnote-label"];
+ } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) {
+ const { href, ariaLabel } = props;
+ child.properties = {
+ href: `#user-content-${String(href).slice(1)}`,
+ dataFootnoteBackref: "",
+ ariaLabel,
+ className: ["data-footnote-backref"],
+ };
+ } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) {
+ props.id = `user-content-${props.id}`;
+ } else if (tagName === "section" && props.dataFootnotes !== undefined) {
+ child.properties = { dataFootnotes: "", className: ["footnotes"] };
+ child.children.unshift({
+ type: "element",
+ tagName: "h2",
+ properties: { className: ["sr-only"], id: "footnote-label" },
+ children: [{ type: "text", value: "Footnotes" }],
+ });
+ } else if (tagName === "a" && typeof props.href === "string") {
+ // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL.
+ const path = windowsPath(props.href);
+ props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href);
+ } else if (tagName === "img" && typeof props.src === "string") {
+ const changeRequest = walk.options.extensions.changeRequest;
+ const src = changeRequest
+ ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl)
+ : props.src;
+ props.src = windowsPath(src) ?? normalizeUri(src);
+ } else if (tagName === "code" && isElement(node, "pre")) {
+ if (props.dataMeta !== undefined) {
+ props.dataCodeMeta = props.dataMeta;
+ delete props.dataMeta;
+ }
+ } else if (tagName === "code" && !inLink) {
+ props.dataInlineCode = "";
+ } else if (tagName === "ol" && walk.options.extensions.userMessage) {
+ keepListNumbers(child, walk.source);
+ } else if (tagName === "li") {
+ const firstBlock = child.children.find(isElementNode);
+ if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) {
+ continue;
+ }
+ // Tight items put the checkbox directly in ``, loose ones inside its first ``.
+ const checkbox = isElement(child.children[0], "input")
+ ? child.children[0]
+ : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input")
+ ? firstBlock.children[0]
+ : undefined;
+ if (checkbox) {
+ props.className = ["task-list-item"];
+ const { checked } = checkbox.properties;
+ checkbox.properties = { type: "checkbox", checked, disabled: true };
+ if (node.type === "element") node.properties.className = ["contains-task-list"];
+ }
+ breakLines(child, walk.options.breaks);
+ } else if (tagName === "p") {
+ breakLines(child, walk.options.breaks);
+ } else if (tagName === "blockquote") {
+ // remarkGithubAlerts
+ const paragraph = child.children.find((item) => item.type === "element");
+ const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
+ const text = first?.type === "text" ? first.value : "";
+ const insight = walk.insightMarker?.exec(text);
+ const alert = GITHUB_ALERT_MARKER.exec(text);
+ // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it.
+ const match = insight
+ ? ([insight[0], "insight"] as const)
+ : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1)
+ ? alert
+ : null;
+ if (match && first?.type === "text" && isElement(paragraph, "p")) {
+ first.value = first.value.slice(match[0].length);
+ if (first.value === "") paragraph.children.shift();
+ if (paragraph.children.length === 0) {
+ const at = child.children.indexOf(paragraph);
+ const next = child.children[at + 1];
+ // The line ending after it goes too, as remark leaves none for a removed paragraph.
+ const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1;
+ child.children.splice(at, blank);
+ }
+ props.dataAlert = match[1]!.toLowerCase();
+ }
+ }
+ transform(
+ child,
+ walk,
+ inLink || tagName === "a",
+ inCode || tagName === "code" || tagName === "pre",
+ );
+ }
+}
+
+/**
+ * remark-breaks puts a ` ` before every soft line ending, and remarkBreakAroundImageLines
+ * before those next to a Markdown image. Both keep the line ending after it.
+ */
+/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */
+function imageOwnsLine(items: ElementContent[], at: number): boolean {
+ if (!isMarkdownImage(items[at])) return false;
+ const before = items[at - 1];
+ const after = items[at + 1];
+ const startsLine =
+ before === undefined ||
+ (before.type === "text" && /\n[ \t]*$/.test(before.value)) ||
+ isElement(before, "br");
+ const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value));
+ return startsLine && endsLine;
+}
+
+const isBlockElement = (node: ElementContent | undefined) =>
+ node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName);
+
+function breakLines(paragraph: Element, breaks: boolean) {
+ const items = paragraph.children;
+ for (let at = 0; at < items.length; at++) {
+ const item = items[at]!;
+ if (
+ item.type === "element" &&
+ breaks &&
+ item.tagName !== "code" &&
+ !CLOSES_PARAGRAPH.has(item.tagName)
+ ) {
+ breakLines(item, breaks);
+ }
+ if (item.type !== "text" || !item.value.includes("\n")) continue;
+ const afterImage = imageOwnsLine(items, at - 1);
+ const beforeImage = imageOwnsLine(items, at + 1);
+ const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li");
+ const beforeBlock =
+ isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li");
+ const lines = item.value.split("\n");
+ const parts: ElementContent[] = [];
+ lines.forEach((line, index) => {
+ // A hard break's own line ending follows its , and adds no second one;
+ // structural line endings around a list item's block children stay breaks between blocks.
+ const afterHardBreak = index === 1 && isElement(items[at - 1], "br");
+ const blockBoundary =
+ (index === 1 && lines[0] === "" && afterBlock) ||
+ (index === lines.length - 1 && line === "" && beforeBlock);
+ const breaksHere =
+ index > 0 &&
+ !afterHardBreak &&
+ !blockBoundary &&
+ (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage));
+ if (index > 0) {
+ if (breaksHere) {
+ const previous = parts.at(-1);
+ if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, "");
+ parts.push(BREAK);
+ }
+ parts.push({ type: "text", value: `\n${line}` });
+ } else if (line) {
+ parts.push({ type: "text", value: line });
+ }
+ });
+ // Rejoin text that did not break, so the tree matches remark's text nodes.
+ const merged: ElementContent[] = [];
+ for (const part of parts) {
+ const previous = merged.at(-1);
+ if (part.type === "text" && previous?.type === "text") previous.value += part.value;
+ else merged.push(part);
+ }
+ items.splice(at, 1, ...merged);
+ at += merged.length - 1;
+ }
+}
+
+/**
+ * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source
+ * Words drew it from, so copying any part of a formula copies the whole of it.
+ */
+// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a
+// table it keeps its width and the table scrolls.
+const MATH_SCROLL = [
+ "max-w-full",
+ "overflow-x-auto",
+ "overflow-y-hidden",
+ "px-0.5",
+ "py-0.75",
+ "in-[.chat-markdown-table-container]:max-w-none",
+ "in-[.chat-markdown-table-container]:overflow-visible",
+];
+
+function mathWrapper(svg: Element): Element {
+ const tex = String(svg.properties.ariaLabel ?? "").trim();
+ const display = /display:\s*block/.test(String(svg.properties.style ?? ""));
+ return {
+ type: "element",
+ tagName: "span",
+ properties: display
+ ? {
+ className: ["chat-markdown-math-display", "block", ...MATH_SCROLL],
+ dataMarkdownMath: "display",
+ dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`,
+ }
+ : {
+ className: ["inline-block", "align-middle", ...MATH_SCROLL],
+ dataMarkdownMath: "inline",
+ dataMarkdownCopy: `\\(${tex}\\)`,
+ },
+ children: [svg],
+ };
+}
+
+function restoreMath(node: Root | Element, math: Map) {
+ const children = node.children as ElementContent[];
+ for (let index = 0; index < children.length; index++) {
+ const child = children[index]!;
+ if (child.type !== "element") continue;
+ const id = child.properties.id;
+ const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined;
+ if (svg) children[index] = mathWrapper(svg);
+ else restoreMath(child, math);
+ }
+}
+
+const addHeadingIds = rehypeHeadingIds();
+const addTextDirection = rehypeTextDirection();
+const preserveImageSourceMeta = rehypePreserveImageSourceMeta();
+const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks();
+const groupChipPunctuation = rehypeChipPunctuation();
+
+const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
+const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
+
+interface InsightSource {
+ readonly source: string;
+ readonly tree: Root;
+ readonly marker: RegExp;
+ /** The offset in the message for an offset in `source`. */
+ readonly toOriginal: (offset: number) => number;
+}
+
+/**
+ * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line
+ * at the same indentation closes; the end of the text closes one that never does. Lines in code
+ * neither open nor close one, and an opening Words does not read as a quote's first line, as in
+ * an HTML block or a quote's lazy line, stays text.
+ */
+function insightSource(text: string, options: RenderOptions): InsightSource | null {
+ if (!text.includes("★ Insight")) return null;
+ const code: Array = [];
+ const findCode = (node: Root | Element) => {
+ for (const child of node.children) {
+ if (child.type !== "element") continue;
+ if (child.tagName === "pre" && child.position) {
+ code.push([child.position.start.offset!, child.position.end.offset!]);
+ } else findCode(child);
+ }
+ };
+ findCode(parse(text, options));
+ const nonce = Math.random().toString(36).slice(2);
+ const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`);
+ const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g");
+ const lines = text.split(/(?<=\n)/u);
+ const skipped = new Set();
+ for (;;) {
+ // Each line's offset in the message and in the source, and how much longer it got.
+ const offsets: Array<{ original: number; source: number; length: number; delta: number }> = [];
+ let original = 0;
+ let rewritten = 0;
+ let opened = 0;
+ let indent: string | undefined;
+ const source = lines
+ .map((line, lineIndex) => {
+ const value = line.replace(/[\r\n]+$/u, "");
+ const ending = line.slice(value.length);
+ const inCode = code.some(([start, end]) => original >= start && original < end);
+ let output = line;
+ if (indent === undefined) {
+ const opening = inCode ? null : INSIGHT_OPENING.exec(value);
+ if (opening && !skipped.has(lineIndex)) {
+ indent = opening[1] ?? "";
+ opened++;
+ output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`;
+ }
+ } else {
+ const closing = inCode ? null : INSIGHT_CLOSING.exec(value);
+ if (closing && closing[1] === indent) {
+ indent = undefined;
+ output = ending;
+ } else output = `> ${line}`;
+ }
+ offsets.push({
+ original,
+ source: rewritten,
+ length: line.length,
+ delta: output.length - line.length,
+ });
+ original += line.length;
+ rewritten += output.length;
+ return output;
+ })
+ .join("");
+ if (opened === 0) return null;
+ const tree = parse(source, options);
+ let stranded = false;
+ const visit = (node: Root | Element, quoteStart: Text | undefined) => {
+ for (const child of node.children) {
+ if (child.type === "text") {
+ for (const found of child.value.matchAll(anywhere)) {
+ if (child === quoteStart && found.index === 0) continue;
+ skipped.add(Number(found[1]));
+ stranded = true;
+ }
+ } else if (child.type === "element") {
+ const paragraph =
+ child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined;
+ const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
+ visit(child, first?.type === "text" ? first : quoteStart);
+ }
+ }
+ };
+ visit(tree, undefined);
+ if (stranded) continue;
+ return {
+ source,
+ tree,
+ marker,
+ toOriginal: (offset) => {
+ const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!;
+ return (
+ line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length)
+ );
+ },
+ };
+ }
+}
+
+/** Positions that point into an insight's rewritten source, moved back into the message. */
+function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) {
+ for (const child of node.children) {
+ if (child.type !== "element") continue;
+ if (child.position) {
+ const start = toOriginal(child.position.start.offset!);
+ const end = toOriginal(child.position.end.offset!);
+ child.position = {
+ start: { line: 1, column: start + 1, offset: start },
+ end: { line: 1, column: end + 1, offset: end },
+ };
+ }
+ restorePositions(child, toOriginal);
+ }
+}
+
+const PREVIEW_SEPARATED = new Set([
+ "blockquote",
+ "ul",
+ "ol",
+ "li",
+ "table",
+ "thead",
+ "tbody",
+ "tr",
+]);
+
+/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */
+function flattenPreview(tree: Root, preview: NonNullable): Root {
+ const children: ElementContent[] = [];
+ let remaining = preview.maxLength;
+ let fragments: string[] = [];
+ const flush = () => {
+ if (fragments.length === 0) return;
+ children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") });
+ fragments = [];
+ };
+ const take = (value: string) => {
+ const text = value.slice(0, remaining);
+ remaining = text.length < value.length ? 0 : remaining - text.length;
+ // A cut must not leave half a surrogate pair.
+ return text.replace(/[\uD800-\uDBFF]$/, "");
+ };
+ const visit = (node: Root | ElementContent) => {
+ if (remaining === 0) return;
+ if (node.type === "text") {
+ fragments.push(take(node.value));
+ return;
+ }
+ if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) {
+ flush();
+ // One line has no room for display math, which a preview shows inline.
+ const svg = node.children[0];
+ children.push(
+ node.properties.dataMarkdownMath === "display" && svg?.type === "element"
+ ? mathWrapper({
+ ...svg,
+ properties: {
+ ...svg.properties,
+ style: "display:inline;vertical-align:middle;overflow:visible",
+ },
+ })
+ : node,
+ );
+ return;
+ }
+ if (node.type === "element" && node.tagName === "img") {
+ fragments.push(take(String(node.properties.alt ?? "")));
+ return;
+ }
+ if (node.type === "element" && node.tagName === "br") {
+ fragments.push(take(" "));
+ return;
+ }
+ if (node.type !== "root" && node.type !== "element") return;
+ const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName);
+ let first = true;
+ for (const child of node.children as ElementContent[]) {
+ if (remaining === 0) break;
+ if (child.type === "text" && child.value.trim() === "" && separates) continue;
+ if (!first && separates) fragments.push(take(" "));
+ first = false;
+ visit(child);
+ }
+ };
+ visit(tree);
+ flush();
+ const head = children[0];
+ const tail = children.at(-1);
+ if (head?.type === "text") head.value = head.value.trimStart();
+ if (tail?.type === "text") tail.value = tail.value.trimEnd();
+ const visible = children.some((child) => child.type !== "text" || child.value);
+ return {
+ type: "root",
+ children: visible ? children : [{ type: "text", value: preview.fallback }],
+ };
+}
+
+/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */
+function makeInert(node: Root | Element) {
+ const children = node.children as ElementContent[];
+ for (let index = 0; index < children.length; index++) {
+ const child = children[index]!;
+ if (child.type !== "element") continue;
+ if (child.tagName === "a") {
+ children.splice(index, 1, ...child.children);
+ index--;
+ continue;
+ }
+ if (child.tagName === "img") {
+ children[index] = { type: "text", value: String(child.properties.alt ?? "") };
+ continue;
+ }
+ if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) {
+ children[index] = { type: "text", value: textOf(child) };
+ continue;
+ }
+ if (
+ child.tagName === "code" &&
+ String(child.properties.className ?? "").includes("language-mermaid")
+ ) {
+ child.properties.className = ["language-text"];
+ }
+ makeInert(child);
+ }
+}
+
+/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */
+export function wordsHast(text: string, options: WordsHastOptions): Root {
+ const { extensions } = options;
+ const renderOptions: RenderOptions = {
+ math: options.math,
+ // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`.
+ texDelimiters: options.math,
+ autolinkBoundaries: true,
+ singleTilde: !extensions.userMessage,
+ leadingWhitespace: extensions.leadingWhitespace === true,
+ windowsPaths: true,
+ codeMeta: true,
+ directives: CODEX_DIRECTIVES,
+ // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes.
+ ...(extensions.preview || extensions.inert
+ ? { skipHtml: true }
+ : { escapeHtml: options.escapeHtml }),
+ };
+ const insights = options.insights ? insightSource(text, renderOptions) : null;
+ const source = insights?.source ?? text;
+ const tree = insights?.tree ?? parse(source, renderOptions);
+ const walk: Walk = {
+ render: (markdown, indent) =>
+ parse(markdown, {
+ ...renderOptions,
+ leadingWhitespace: extensions.leadingWhitespace === true && { indent },
+ }),
+ source,
+ options,
+ math: new Map(),
+ mathKey: `t3-math-${Math.random().toString(36).slice(2)}`,
+ insightMarker: insights?.marker ?? null,
+ };
+ transform(tree, walk, false, false);
+ preserveImageSourceMeta(tree as never);
+ normalizeLocalEditorLinks(tree as never);
+ const hast = sanitizeChatHast(tree);
+ if (walk.math.size > 0) restoreMath(hast, walk.math);
+ if (insights) restorePositions(hast, insights.toOriginal);
+ if (extensions.inert) makeInert(hast);
+ if (extensions.preview) return flattenPreview(hast, extensions.preview);
+ addHeadingIds(hast);
+ addTextDirection(hast as never);
+ groupChipPunctuation(hast as never);
+ return hast;
+}
+
+export interface CodexDirectiveSource {
+ readonly name: string;
+ readonly attributes: Record;
+ /** UTF-16 offsets of the whole directive in the source. */
+ readonly start: number;
+ readonly end: number;
+ /** The label's text as written. */
+ readonly label: string;
+ /** Inside a link, where a file citation stays text. */
+ readonly inLink: boolean;
+}
+
+/** The Codex directives in `markdown`, as Words reads them. */
+export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] {
+ const found: CodexDirectiveSource[] = [];
+ const visit = (node: Root | Element, inLink: boolean) => {
+ for (const child of node.children) {
+ if (child.type !== "element") continue;
+ const name = child.properties.dataDirective;
+ if (typeof name === "string" && child.position) {
+ const { start, end } = child.position;
+ found.push({
+ name,
+ attributes: directiveAttributes(child),
+ start: start.offset!,
+ end: end.offset!,
+ label: directiveLabel(markdown.slice(start.offset, end.offset)),
+ inLink,
+ });
+ }
+ visit(child, inLink || child.tagName === "a");
+ }
+ };
+ visit(
+ parse(markdown, {
+ windowsPaths: true,
+ autolinkBoundaries: true,
+ directives: CODEX_DIRECTIVES,
+ }),
+ false,
+ );
+ return found;
+}
+
+/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */
+function directiveLabel(written: string): string {
+ const open = written.indexOf("[");
+ if (open < 0) return "";
+ let depth = 0;
+ for (let index = open; index < written.length; index++) {
+ const character = written[index];
+ if (character === "\\") index++;
+ else if (character === "[") depth++;
+ else if (character === "]" && --depth === 0) return written.slice(open + 1, index);
+ }
+ return "";
+}
+
+/**
+ * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks,
+ * links, list items and math carry source positions.
+ */
+export function markdownTree(
+ markdown: string,
+ options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {},
+): Root {
+ return parse(markdown, {
+ windowsPaths: true,
+ autolinkBoundaries: true,
+ skipHtml: options.skipHtml === true,
+ singleTilde: options.singleTilde !== false,
+ math: options.math === true,
+ texDelimiters: options.math === true,
+ });
+}
+
+/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */
+export function markdownMathRanges(text: string): Array<{ start: number; end: number }> {
+ if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return [];
+ const ranges: Array<{ start: number; end: number }> = [];
+ const visit = (node: Root | Element) => {
+ for (const child of node.children) {
+ if (child.type !== "element") continue;
+ if (child.tagName === "svg") {
+ if (child.position) {
+ ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! });
+ }
+ continue;
+ }
+ visit(child);
+ }
+ };
+ visit(parse(text, { math: true, texDelimiters: true }));
+ return ranges;
+}
+
+/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */
+export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> {
+ const openers = [...markdown.matchAll(/", start + 4);
+ return { start, end: close < 0 ? markdown.length : close + 3 };
+ });
+}
+
+/**
+ * The first definition of each label in `markdown`, as one line of Markdown. Words decides which
+ * `[label]:` text defines one: each label is looked up again after the text.
+ */
+export function markdownReferenceDefinitions(markdown: string): string[] {
+ const labels = new Map();
+ for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) {
+ const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase();
+ // `[^1]:` is a footnote.
+ if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!);
+ }
+ if (labels.size === 0) return [];
+ let probe = `${markdown}\n\n`;
+ const lookups = new Map();
+ for (const label of labels.values()) {
+ lookups.set(probe.length, label);
+ probe += `[${label}]\n\n`;
+ }
+ const definitions: string[] = [];
+ const visit = (node: Root | Element) => {
+ for (const child of node.children) {
+ if (child.type !== "element") continue;
+ const label = lookups.get(child.position?.start.offset ?? -1);
+ if (child.tagName === "a" && label !== undefined) {
+ const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent);
+ const title = child.properties.title;
+ definitions.push(
+ `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`,
+ );
+ } else visit(child);
+ }
+ };
+ visit(parse(probe, { windowsPaths: true }));
+ return definitions;
+}
diff --git a/apps/web/src/routes/_chat.settings.inference.tsx b/apps/web/src/routes/_chat.settings.inference.tsx
index 675886f07a6eb..d6a5f01aa18ef 100644
--- a/apps/web/src/routes/_chat.settings.inference.tsx
+++ b/apps/web/src/routes/_chat.settings.inference.tsx
@@ -1,16 +1,20 @@
+import { T, Var, useGT } from "gt-react";
import { createFileRoute } from "@tanstack/react-router";
import { InferenceSettings } from "../components/settings/InferenceSettings";
import { useSettingsScope } from "../components/settings/SettingsScopeContext";
function SettingsInferenceRoute() {
+ const gt = useGT();
const { environment, scope } = useSettingsScope();
if (!environment) {
return (
{scope.kind === "environment"
- ? `Reconnect ${scope.label} to manage inference accounts.`
- : "Connect an environment to manage inference accounts."}
+ ? gt("Reconnect {environment} to manage inference accounts.", {
+ environment: scope.label,
+ })
+ : gt("Connect an environment to manage inference accounts.")}
);
}
@@ -23,7 +27,9 @@ function SettingsInferenceRoute() {
);
return (
- Update T3 Code on {environment.label} to manage inference accounts.
+
+ Update T3 Code on {environment.label} to manage inference accounts.
+
);
}
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index d535723cca96a..8bc66e6694d13 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -694,6 +694,10 @@
"./provider-instance-ids": {
"types": "./src/providerInstanceIds.ts",
"default": "./src/providerInstanceIds.ts"
+ },
+ "./pull-request-references": {
+ "types": "./src/pullRequestReferences.ts",
+ "default": "./src/pullRequestReferences.ts"
}
},
"scripts": {
@@ -721,16 +725,16 @@
"effect": "catalog:",
"gt-i18n": "1.0.40",
"jszip": "3.10.1",
- "remark-gfm": "catalog:",
- "remark-parse": "catalog:",
"three": "0.180.0",
- "unbash": "^5.0.0",
- "unified": "catalog:"
+ "unbash": "^5.0.0"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/mdast": "^4.0.4",
"@types/three": "0.180.0",
+ "remark-gfm": "catalog:",
+ "remark-parse": "catalog:",
+ "unified": "catalog:",
"vite-plus": "catalog:"
}
}
diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts
index f54c1c416d4c6..1c23ffbd9805b 100644
--- a/packages/client-runtime/src/conversationSummaries/index.ts
+++ b/packages/client-runtime/src/conversationSummaries/index.ts
@@ -6,6 +6,8 @@ import {
type OrchestrationV2MessageProvenance,
} from "@t3tools/contracts";
import type { Atom } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import { createEnvironmentRpcQueryAtomFamily } from "../state/runtime.ts";
@@ -30,18 +32,26 @@ export function createConversationSummariesAtoms(
};
}
-export function conversationSummaryPassLabel(pass: ConversationSummaryPass): string {
+export function conversationSummaryPassLabel(
+ pass: ConversationSummaryPass,
+ resolve: MFunctionType = mFallback,
+): string {
const waiting =
pass.waitingMessages === 0
? ""
- : ` ${pass.waitingMessages} older ${pass.waitingMessages === 1 ? "source waits" : "sources wait"} for a summary.`;
+ : ` ${resolve(
+ msg(
+ "{count, plural, one {# older source waits for a summary.} other {# older sources wait for a summary.}}",
+ ),
+ { count: pass.waitingMessages },
+ )}`;
switch (pass.result) {
case "ran":
- return `Last pass wrote ${pass.generated} ${pass.generated === 1 ? "summary" : "summaries"}.${pass.reason ? ` ${pass.reason}` : ""}${waiting}`;
+ return `${resolve(msg("Last pass wrote {count, plural, one {# summary} other {# summaries}}."), { count: pass.generated })}${pass.reason ? ` ${pass.reason}` : ""}${waiting}`;
case "skipped":
- return `Last pass wrote nothing. ${pass.reason ?? ""}${waiting}`.trim();
+ return `${resolve(msg("Last pass wrote nothing."))} ${pass.reason ?? ""}${waiting}`.trim();
case "failed":
- return `Last pass failed. ${pass.reason ?? ""}${waiting}`.trim();
+ return `${resolve(msg("Last pass failed."))} ${pass.reason ?? ""}${waiting}`.trim();
}
}
@@ -55,15 +65,21 @@ export function messageAuthorLabel(
role: "user" | "assistant",
speaker?: { readonly label: string; readonly model: string },
provenance?: OrchestrationV2MessageProvenance,
+ resolve: MFunctionType = mFallback,
): string {
if (provenance?.linkedSender !== undefined) {
const sender = provenance.linkedSender;
- return `Agent: ${sender.title || sender.threadId} (${sender.environmentId})`;
+ return resolve(msg("Agent: {title} ({environment})"), {
+ title: sender.title || sender.threadId,
+ environment: sender.environmentId,
+ });
}
- if (provenance?.senderThreadId !== undefined) return `Agent (${provenance.senderThreadId})`;
- if (provenance !== undefined) return provenance.createdBy === "system" ? "System" : "Agent";
- if (role === "user") return "User";
- if (speaker === undefined) return "Assistant";
+ if (provenance?.senderThreadId !== undefined)
+ return resolve(msg("Agent ({thread})"), { thread: provenance.senderThreadId });
+ if (provenance !== undefined)
+ return resolve(provenance.createdBy === "system" ? msg("System") : msg("Agent"));
+ if (role === "user") return resolve(msg("User"));
+ if (speaker === undefined) return resolve(msg("Assistant"));
// A seat without a label is named by its model.
return speaker.label === speaker.model ? speaker.label : `${speaker.label} (${speaker.model})`;
}
@@ -72,22 +88,26 @@ export function messageAuthorLabel(
export function conversationSummarySourceLabel(
ref: ConversationSummarySourceRef,
result: ConversationSummarySourceResult,
+ resolve: MFunctionType = mFallback,
): string {
- if (result.state !== "available") return "Unavailable";
+ if (result.state !== "available") return resolve(msg("Unavailable"));
switch (result.role) {
case "user":
case "assistant":
- return messageAuthorLabel(result.role, result.speaker, result.provenance);
+ return messageAuthorLabel(result.role, result.speaker, result.provenance, resolve);
case "tool":
- return "Tool";
+ return resolve(msg("Tool"));
case "summary":
- return ref.kind === "summary" ? `Summary ${ref.summaryId}` : "Summary";
+ return ref.kind === "summary"
+ ? resolve(msg("Summary {id}"), { id: ref.summaryId })
+ : resolve(msg("Summary"));
}
}
export function conversationSummarySourceRangeLabel(
ref: ConversationSummarySourceRef,
result: ConversationSummarySourceResult,
+ resolve: MFunctionType = mFallback,
): string | null {
if (result.state !== "available" || result.text.length === 0) return null;
const textOffset = result.textOffset ?? 0;
@@ -97,5 +117,9 @@ export function conversationSummarySourceRangeLabel(
const start = (range?.start ?? 0) + textOffset;
const end = start + result.text.length;
const total = range?.total ?? totalChars;
- return `Characters ${(start + 1).toLocaleString()}–${end.toLocaleString()} of ${total.toLocaleString()}`;
+ return resolve(msg("Characters {start, number}–{end, number} of {total, number}"), {
+ start: start + 1,
+ end,
+ total,
+ });
}
diff --git a/packages/client-runtime/src/externalHistory/index.ts b/packages/client-runtime/src/externalHistory/index.ts
index dbe4623be9962..9af25898f503d 100644
--- a/packages/client-runtime/src/externalHistory/index.ts
+++ b/packages/client-runtime/src/externalHistory/index.ts
@@ -1,9 +1,12 @@
import {
+ type ExternalHistoryMatch,
type ExternalHistorySource,
type ExternalHistoryRequest,
WS_METHODS,
} from "@t3tools/contracts";
import type { Atom } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import { createEnvironmentRpcQueryAtomFamily } from "../state/runtime.ts";
@@ -20,13 +23,20 @@ export function createExternalHistoryAtoms(
};
}
-export function externalHistoryRangeLabel(source: {
- readonly textOffset: number;
- readonly text: string;
- readonly totalChars: number;
-}): string {
+export function externalHistoryRangeLabel(
+ source: {
+ readonly textOffset: number;
+ readonly text: string;
+ readonly totalChars: number;
+ },
+ resolve: MFunctionType = mFallback,
+): string {
const start = source.text.length === 0 ? source.textOffset : source.textOffset + 1;
- return `Characters ${start.toLocaleString()}–${(source.textOffset + source.text.length).toLocaleString()} of ${source.totalChars.toLocaleString()}`;
+ return resolve(msg("Characters {start, number}–{end, number} of {total, number}"), {
+ start,
+ end: source.textOffset + source.text.length,
+ total: source.totalChars,
+ });
}
export function externalHistorySearchFilters(
@@ -41,12 +51,24 @@ export function externalHistorySearchFilters(
};
}
-export function externalHistorySourceStatusLabel(status: ExternalHistorySource["status"]): string {
- return {
- ready: "Ready",
- unavailable: "Cannot read",
- unsupported_format: "Unsupported history format",
- }[status];
+export function externalHistorySourceStatusLabel(
+ status: ExternalHistorySource["status"],
+ resolve: MFunctionType = mFallback,
+): string {
+ return resolve(
+ {
+ ready: msg("Ready"),
+ unavailable: msg("Cannot read"),
+ unsupported_format: msg("Unsupported history format"),
+ }[status],
+ );
+}
+
+export function externalHistoryRoleLabel(
+ role: ExternalHistoryMatch["role"],
+ resolve: MFunctionType = mFallback,
+): string {
+ return resolve({ user: msg("User"), assistant: msg("Assistant"), tool: msg("Tool") }[role]);
}
export {
diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts
index 39b90e2414d0e..9196fbeda9bc8 100644
--- a/packages/client-runtime/src/handoff.ts
+++ b/packages/client-runtime/src/handoff.ts
@@ -15,6 +15,8 @@ import {
} from "@t3tools/shared/model";
import { formatTokens } from "@t3tools/shared/usageFormat";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import { isReasoningSelect } from "./modelTraits.ts";
import type { ThreadStructure } from "./state/models.ts";
@@ -56,10 +58,16 @@ export function resolvePendingHandoff(
}
/** The timeline receipt for a conversation T3 restarted from summaries. */
-export function contextRestartReceipt(restart: OrchestrationV2ContextRestart) {
+export function contextRestartReceipt(
+ restart: OrchestrationV2ContextRestart,
+ resolve: MFunctionType = mFallback,
+) {
return {
- label: "Restarted from summaries",
- detail: `${formatTokens(restart.usedTokens)} tokens passed the ${formatTokens(restart.aboveTokens)} limit`,
+ label: resolve(msg("Restarted from summaries")),
+ detail: resolve(msg("{used} tokens passed the {limit} limit"), {
+ used: formatTokens(restart.usedTokens),
+ limit: formatTokens(restart.aboveTokens),
+ }),
};
}
diff --git a/packages/client-runtime/src/modelEvaluations/index.ts b/packages/client-runtime/src/modelEvaluations/index.ts
index 211e91bcabf07..bfcf4352f0357 100644
--- a/packages/client-runtime/src/modelEvaluations/index.ts
+++ b/packages/client-runtime/src/modelEvaluations/index.ts
@@ -8,6 +8,8 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import type { Atom } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import {
@@ -84,20 +86,28 @@ export function modelEvaluationSelectionLabel(selection: ModelSelection): string
}
const SCORE_LABELS = {
- taskCompletion: "Task completion",
- correctness: "Correctness",
- instructionFollowing: "Instruction following",
- verification: "Verification",
+ taskCompletion: msg("Task completion", { $context: "model evaluation score dimension" }),
+ correctness: msg("Correctness", { $context: "model evaluation score dimension" }),
+ instructionFollowing: msg("Instruction following", {
+ $context: "model evaluation score dimension",
+ }),
+ verification: msg("Verification", { $context: "model evaluation score dimension" }),
} as const;
-export function modelEvaluationScoreRows(guidance: ModelEvaluationGuidance) {
+export function modelEvaluationScoreRows(
+ guidance: ModelEvaluationGuidance,
+ resolve: MFunctionType = mFallback,
+) {
return Object.entries(SCORE_LABELS).map(([key, label]) => {
const dimension = key as keyof typeof SCORE_LABELS;
const score = guidance.meanScores[dimension];
return {
key,
- label,
- value: score === null ? "Not established" : `${score.toFixed(1)} / 4`,
+ label: resolve(label),
+ value:
+ score === null
+ ? resolve(msg("Not established", { $context: "model evaluation score without evidence" }))
+ : `${score.toFixed(1)} / 4`,
count: guidance.scoreCounts[dimension],
};
});
diff --git a/packages/client-runtime/src/projectCode/index.ts b/packages/client-runtime/src/projectCode/index.ts
index 3bc2629427936..620ecdd657734 100644
--- a/packages/client-runtime/src/projectCode/index.ts
+++ b/packages/client-runtime/src/projectCode/index.ts
@@ -9,6 +9,8 @@ import {
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import {
@@ -125,20 +127,22 @@ export type ProjectCodeIndexBadge = {
};
const REFRESH_DETAIL = {
- building: "A newer index is being built.",
- failed: "The last refresh failed, so this index is still answering.",
+ building: msg("A newer index is being built."),
+ failed: msg("The last refresh failed, so this index is still answering."),
} as const;
const FIRST_INDEX_BADGE: Record<"building" | "failed", ProjectCodeIndexBadge> = {
building: {
- label: "Indexing",
+ label: msg("Indexing"),
tone: "muted",
- detail: "Building the first index for this checkout.",
+ detail: msg("Building the first index for this checkout."),
},
failed: {
- label: "Index failed",
+ label: msg("Index failed"),
tone: "warn",
- detail: "Building the first index for this checkout failed. The next code query tries again.",
+ detail: msg(
+ "Building the first index for this checkout failed. The next code query tries again.",
+ ),
},
};
@@ -148,59 +152,81 @@ const FIRST_INDEX_BADGE: Record<"building" | "failed", ProjectCodeIndexBadge> =
*/
export function projectCodeIndexBadge(
index: ProjectCodeIndexInfo | undefined,
+ resolve: MFunctionType = mFallback,
): ProjectCodeIndexBadge {
- const badge = describeIndexState(index);
+ const badge = describeIndexState(index, resolve);
if (index?.refresh === undefined) return badge;
- if (index.state === "unindexed") return FIRST_INDEX_BADGE[index.refresh];
- return { ...badge, detail: `${badge.detail} ${REFRESH_DETAIL[index.refresh]}` };
+ if (index.state === "unindexed") {
+ const first = FIRST_INDEX_BADGE[index.refresh];
+ return { ...first, label: resolve(first.label), detail: resolve(first.detail) };
+ }
+ return { ...badge, detail: `${badge.detail} ${resolve(REFRESH_DETAIL[index.refresh])}` };
}
-function describeIndexState(index: ProjectCodeIndexInfo | undefined): ProjectCodeIndexBadge {
+function describeIndexState(
+ index: ProjectCodeIndexInfo | undefined,
+ resolve: MFunctionType,
+): ProjectCodeIndexBadge {
if (index === undefined) {
return {
- label: "Unavailable",
+ label: resolve(msg("Unavailable")),
tone: "muted",
- detail: "This server does not report index freshness.",
+ detail: resolve(msg("This server does not report index freshness.")),
};
}
const indexedAt = index.indexedCommit === null ? null : index.indexedCommit.slice(0, 7);
switch (index.state) {
case "ready":
return {
- label: "Ready",
+ label: resolve(msg("Ready")),
tone: "ok",
detail:
indexedAt === null
- ? `Index generation ${index.generation} matches the checkout.`
- : `Index generation ${index.generation} matches the checkout at ${indexedAt}.`,
+ ? resolve(msg("Index generation {generation} matches the checkout."), {
+ generation: index.generation,
+ })
+ : resolve(msg("Index generation {generation} matches the checkout at {commit}."), {
+ generation: index.generation,
+ commit: indexedAt,
+ }),
};
case "partial":
return {
- label: "Partial",
+ label: resolve(msg("Partial")),
tone: "warn",
- detail: "Some files are not indexed or references are unresolved. Results may be missing.",
+ detail: resolve(
+ msg("Some files are not indexed or references are unresolved. Results may be missing."),
+ ),
};
case "stale": {
- const files = `${index.changedFiles} ${index.changedFiles === 1 ? "file has" : "files have"} changed since indexing.`;
const moved =
indexedAt !== null && index.headCommit !== null && index.headCommit !== index.indexedCommit;
return {
- label: moved ? `Stale @${indexedAt}` : "Stale",
+ label: moved
+ ? resolve(msg("Stale @{commit}"), { commit: indexedAt })
+ : resolve(msg("Stale")),
tone: "warn",
- detail: `${files} Code queries refresh the index, and so do agent turns while automatic indexing is on.`,
+ detail: resolve(
+ msg(
+ "{count, plural, one {{count} file has changed since indexing.} other {{count} files have changed since indexing.}} Code queries refresh the index, and so do agent turns while automatic indexing is on.",
+ ),
+ { count: index.changedFiles },
+ ),
};
}
case "indexing":
return {
- label: "Indexing",
+ label: resolve(msg("Indexing")),
tone: "muted",
- detail: "Another code query is indexing this checkout.",
+ detail: resolve(msg("Another code query is indexing this checkout.")),
};
case "unindexed":
return {
- label: "Not indexed",
+ label: resolve(msg("Not indexed")),
tone: "muted",
- detail: "This checkout has not been indexed yet. The first code query indexes it.",
+ detail: resolve(
+ msg("This checkout has not been indexed yet. The first code query indexes it."),
+ ),
};
}
}
diff --git a/packages/client-runtime/src/projectKnowledge/index.test.ts b/packages/client-runtime/src/projectKnowledge/index.test.ts
index bb233d16e2d79..061a0e49f9538 100644
--- a/packages/client-runtime/src/projectKnowledge/index.test.ts
+++ b/packages/client-runtime/src/projectKnowledge/index.test.ts
@@ -128,7 +128,7 @@ it("traces trust from before the first recorded event through each feedback", ()
];
expect(projectFactTrustPoints(history)).toEqual([0.5, 0.55, 0.45]);
expect(projectFactTrustPoints(history.slice(1))).toEqual([0.5, 0.55, 0.45]);
- expect(history.map(projectFactHistoryLabel)).toEqual([
+ expect(history.map((entry) => projectFactHistoryLabel(entry))).toEqual([
"History begins at revision 1",
"Marked helpful",
"Marked unhelpful",
diff --git a/packages/client-runtime/src/projectKnowledge/index.ts b/packages/client-runtime/src/projectKnowledge/index.ts
index 72d335a0363b3..f29f1ae813bc1 100644
--- a/packages/client-runtime/src/projectKnowledge/index.ts
+++ b/packages/client-runtime/src/projectKnowledge/index.ts
@@ -12,6 +12,8 @@ import {
} from "@t3tools/contracts";
export { projectKnowledgeContextRecord } from "@t3tools/shared/composerContextReferences";
import type { Atom } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import {
createEnvironmentRpcCommand,
@@ -102,25 +104,37 @@ export function deliveredKnowledgeSnapshot(result: ProjectKnowledgeDeliveries, c
export function deliveredKnowledgeNotes(
snapshot: NonNullable>,
+ resolve: MFunctionType = mFallback,
): ReadonlyArray {
const notes: string[] = [];
if (snapshot.recallFailed)
- notes.push("Optional knowledge recall failed; historical evidence was omitted.");
+ notes.push(resolve(msg("Optional knowledge recall failed; historical evidence was omitted.")));
if (snapshot.status === "prepared" || snapshot.status === "uncertain")
- notes.push("Delivery to the provider was not confirmed.");
- if (snapshot.status === "failed") notes.push("This turn was not sent to the provider.");
- if (snapshot.attempts > 1) notes.push(`Prepared for ${snapshot.attempts} provider attempts.`);
+ notes.push(resolve(msg("Delivery to the provider was not confirmed.")));
+ if (snapshot.status === "failed")
+ notes.push(resolve(msg("This turn was not sent to the provider.")));
+ if (snapshot.attempts > 1)
+ notes.push(
+ resolve(
+ msg(
+ "Prepared for {attempts, plural, one {{attempts} provider attempt} other {{attempts} provider attempts}}.",
+ ),
+ { attempts: snapshot.attempts },
+ ),
+ );
if (snapshot.item === null) return notes;
if (snapshot.item.current === "changed")
- notes.push("This knowledge has changed since it was sent.");
+ notes.push(resolve(msg("This knowledge has changed since it was sent.")));
if (snapshot.item.contentRemoved)
notes.push(
- "This knowledge has since been forgotten. Its content was removed from this record.",
+ resolve(
+ msg("This knowledge has since been forgotten. Its content was removed from this record."),
+ ),
);
else if (snapshot.item.current === "forgotten")
- notes.push("This knowledge has since been forgotten.");
+ notes.push(resolve(msg("This knowledge has since been forgotten.")));
if (snapshot.item.current === "unavailable")
- notes.push("A source for this knowledge is no longer available.");
+ notes.push(resolve(msg("A source for this knowledge is no longer available.")));
return notes;
}
@@ -128,71 +142,108 @@ export const KNOWLEDGE_DELIVERY_OMISSION_LABEL: Record<
DeliveryRecord["omissions"][number]["reason"],
string
> = {
- not_referenced: "not referenced in the message",
- over_budget: "exceeds the context allowance",
- source_unavailable: "source unavailable",
- stale_revision: "selected revision could not be verified",
- not_permitted: "source not permitted for this project",
- recall_failed: "optional knowledge recall failed",
+ not_referenced: msg("not referenced in the message"),
+ over_budget: msg("exceeds the context allowance"),
+ source_unavailable: msg("source unavailable"),
+ stale_revision: msg("selected revision could not be verified"),
+ not_permitted: msg("source not permitted for this project"),
+ recall_failed: msg("optional knowledge recall failed"),
};
export const KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL: Record =
{
- missing: "Source missing",
- deleted: "Source deleted",
- archived: "Source archived",
- wrong_project: "Source moved",
- streaming: "Source still streaming",
- changed: "Source changed",
+ missing: msg("Source missing"),
+ deleted: msg("Source deleted"),
+ archived: msg("Source archived"),
+ wrong_project: msg("Source moved"),
+ streaming: msg("Source still streaming"),
+ changed: msg("Source changed"),
};
-export function knowledgeOriginLabel(origin: KnowledgeOrigin): string {
+export const KNOWLEDGE_FACT_KIND_LABEL: Record = {
+ decision: msg("decision", { $context: "project fact kind" }),
+ constraint: msg("constraint", { $context: "project fact kind" }),
+ convention: msg("convention", { $context: "project fact kind" }),
+ note: msg("note", { $context: "project fact kind" }),
+};
+
+export const KNOWLEDGE_FACT_STATUS_LABEL: Record = {
+ saved: msg("saved", { $context: "project fact status" }),
+ forgotten: msg("forgotten", { $context: "project fact status" }),
+};
+
+export function knowledgeOriginLabel(
+ origin: KnowledgeOrigin,
+ resolve: MFunctionType = mFallback,
+): string {
switch (origin.kind) {
case "user":
- return "User assertion";
+ return resolve(msg("User assertion"));
case "agent-thread":
- return `Agent observation in thread ${origin.threadId}`;
+ return resolve(msg("Agent observation in thread {threadId}"), { threadId: origin.threadId });
case "agent-client":
- return `Agent observation from ${origin.label}`;
+ return resolve(msg("Agent observation from {label}"), { label: origin.label });
case "assisted":
return origin.runOutcome === "completed"
- ? "Learned from a finished run"
- : `Learned from a run that ${origin.runOutcome === "failed" ? "failed" : "was interrupted"}`;
+ ? resolve(msg("Learned from a finished run"))
+ : origin.runOutcome === "failed"
+ ? resolve(msg("Learned from a run that failed"))
+ : resolve(msg("Learned from a run that was interrupted"));
case "curator":
- return "Memory curator";
+ return resolve(msg("Memory curator"));
case "unknown":
- return "Origin not recognized by this version";
+ return resolve(msg("Origin not recognized by this version"));
}
}
-export function assistedLearningRunLabel(run: AssistedLearningRun): string {
+export function assistedLearningRunLabel(
+ run: AssistedLearningRun,
+ resolve: MFunctionType = mFallback,
+): string {
switch (run.result) {
case "ran":
return run.saved === 0
- ? `Last run: nothing saved.${run.reason ? ` ${run.reason}` : ""}`
- : `Last run: saved ${run.saved}.${run.reason ? ` ${run.reason}` : ""}`;
+ ? resolve(msg("Last run: nothing saved.{reason}"), {
+ reason: run.reason ? ` ${run.reason}` : "",
+ })
+ : resolve(msg("Last run: saved {saved}.{reason}"), {
+ saved: run.saved,
+ reason: run.reason ? ` ${run.reason}` : "",
+ });
case "skipped":
- return `Last run skipped. ${run.reason ?? ""}`.trim();
+ return resolve(msg("Last run skipped. {reason}"), { reason: run.reason ?? "" }).trim();
case "failed":
- return `Last run failed. ${run.reason ?? ""}`.trim();
+ return resolve(msg("Last run failed. {reason}"), { reason: run.reason ?? "" }).trim();
}
}
/** The fact's recall eligibility as one line; the caller appends the formatted date. */
-export function projectFactVerdictLabel(verdict: ProjectFactVerdictRecord): string {
- const decided =
- verdict.by === "check"
- ? "checked"
- : verdict.by === "person"
- ? "marked by you"
- : "marked by an agent";
+export function projectFactVerdictLabel(
+ verdict: ProjectFactVerdictRecord,
+ resolve: MFunctionType = mFallback,
+): string {
switch (verdict.value) {
case "standing":
- return `Standing, recalled into related work · ${decided}`;
+ return resolve(
+ msg(
+ "Standing, recalled into related work · {by, select, check {checked} person {marked by you} other {marked by an agent}}",
+ ),
+ { by: verdict.by },
+ );
case "task":
- return `Set aside as a task note, never recalled automatically · ${decided}`;
+ return resolve(
+ msg(
+ "Set aside as a task note, never recalled automatically · {by, select, check {checked} person {marked by you} other {marked by an agent}}",
+ ),
+ { by: verdict.by },
+ );
case "code":
- return `Set aside as a code description, never recalled automatically · ${decided}`;
+ return resolve(
+ msg(
+ "Set aside as a code description, never recalled automatically · {by, select, check {checked} person {marked by you} other {marked by an agent}}",
+ ),
+ { by: verdict.by },
+ );
}
}
@@ -209,51 +260,64 @@ export function canRestoreFactToRecall(fact: ProjectFact): boolean {
export function memoryCurationRunLabel(
run: NonNullable,
+ resolve: MFunctionType = mFallback,
): string {
const explanation =
run.reason === "disabled"
- ? "Memory curation is turned off for this project."
+ ? resolve(msg("Memory curation is turned off for this project."))
: run.reason === "provider_unsupported"
- ? "The selected model does not support memory curation."
+ ? resolve(msg("The selected model does not support memory curation."))
: run.reason === "project_unavailable"
- ? "The project is archived or unavailable."
+ ? resolve(msg("The project is archived or unavailable."))
: run.reason === "nothing_to_review"
- ? "No eligible memories to review."
+ ? resolve(msg("No eligible memories to review."))
: run.reason === "invalid_output"
- ? "The model returned an unusable review."
+ ? resolve(msg("The model returned an unusable review."))
: run.reason === "interrupted"
- ? "The review was interrupted."
+ ? resolve(msg("The review was interrupted."))
: "";
switch (run.status) {
case "running":
- return "Reviewing project memory…";
+ return resolve(msg("Reviewing project memory…"));
case "ran":
- return `Last review: ${run.reviewed} reviewed, ${run.changed} changed.`;
+ return resolve(msg("Last review: {reviewed} reviewed, {changed} changed."), {
+ reviewed: run.reviewed,
+ changed: run.changed,
+ });
case "skipped":
- return `Last review skipped. ${explanation}`.trim();
+ return resolve(msg("Last review skipped. {explanation}"), { explanation }).trim();
case "failed":
- return `Last review could not finish. ${explanation}`.trim();
+ return resolve(msg("Last review could not finish. {explanation}"), { explanation }).trim();
}
}
-export function projectFactHistoryLabel(entry: ProjectFactHistoryEntry): string {
- if (entry.memoryAction === "curated") return "Removed automatically";
- if (entry.memoryAction === "restored") return "Restored to recall";
+export function projectFactHistoryLabel(
+ entry: ProjectFactHistoryEntry,
+ resolve: MFunctionType = mFallback,
+): string {
+ if (entry.memoryAction === "curated") return resolve(msg("Removed automatically"));
+ if (entry.memoryAction === "restored") return resolve(msg("Restored to recall"));
switch (entry.event) {
case "baseline":
- return `History begins at revision ${entry.revision}`;
+ return resolve(msg("History begins at revision {revision}"), { revision: entry.revision });
case "created":
- return entry.relatedFactId === null ? "Created" : "Created as a replacement";
+ return entry.relatedFactId === null
+ ? resolve(msg("Created", { $context: "project fact history" }))
+ : resolve(msg("Created as a replacement"));
case "edited":
- return `Edited to revision ${entry.revision}`;
+ return resolve(msg("Edited to revision {revision}"), { revision: entry.revision });
case "confirmed":
- return "Confirmed";
+ return resolve(msg("Confirmed", { $context: "project fact history" }));
case "forgotten":
- return entry.actor.kind === "curator" ? "Removed automatically" : "Forgotten";
+ return entry.actor.kind === "curator"
+ ? resolve(msg("Removed automatically"))
+ : resolve(msg("Forgotten", { $context: "project fact history" }));
case "feedback":
- return entry.helpful === false ? "Marked unhelpful" : "Marked helpful";
+ return entry.helpful === false
+ ? resolve(msg("Marked unhelpful"))
+ : resolve(msg("Marked helpful"));
case "superseded":
- return "Superseded";
+ return resolve(msg("Superseded", { $context: "project fact history" }));
}
}
@@ -269,13 +333,16 @@ export function projectFactTrustPoints(
];
}
-export function knowledgeConflictHintLabel(hint: KnowledgeConflictHint): string {
+export function knowledgeConflictHintLabel(
+ hint: KnowledgeConflictHint,
+ resolve: MFunctionType = mFallback,
+): string {
switch (hint.kind) {
case "duplicate":
- return "Same as an existing fact";
+ return resolve(msg("Same as an existing fact"));
case "near_duplicate":
- return "Possible duplicate of";
+ return resolve(msg("Possible duplicate of"));
case "possible_conflict":
- return "Possible conflict with";
+ return resolve(msg("Possible conflict with"));
}
}
diff --git a/packages/client-runtime/src/providerClients.ts b/packages/client-runtime/src/providerClients.ts
index 83344ccee92cd..3c2cd513e1e9e 100644
--- a/packages/client-runtime/src/providerClients.ts
+++ b/packages/client-runtime/src/providerClients.ts
@@ -16,6 +16,8 @@ import { kiroClient } from "@t3tools/provider-kiro/client";
import { museClient } from "@t3tools/provider-muse/client";
import { openCodeClient } from "@t3tools/provider-opencode/client";
import { piClient } from "@t3tools/provider-pi/client";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
// OpenRouter's Ink and Cloud glyphs from https://openrouter.ai/brand.
export const openRouterIcon: ProviderIcon = {
@@ -67,14 +69,21 @@ export function getProviderClient(driver: string | null | undefined) {
export function unavailableModelReason(
provider: Pick | null | undefined,
slug: string,
+ resolve: MFunctionType = mFallback,
): string | null {
const model = provider?.models.find(
(entry) => entry.slug === slug || entry.aliases?.includes(slug),
);
if (provider?.requiresListedModel && !model)
- return "This model is no longer available from this provider. Choose another model.";
+ return resolve(
+ msg("This model is no longer available from this provider. Choose another model."),
+ );
return model?.isUnavailable
- ? `${model.name} is temporarily unavailable. Choose another model or try again later.`
+ ? resolve(
+ msg("{model} is temporarily unavailable. Choose another model or try again later.", {
+ model: model.name,
+ }),
+ )
: null;
}
diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts
index d4f19173758ec..7d9d162d76a05 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.test.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts
@@ -4,19 +4,39 @@ import remarkParse from "remark-parse";
import { unified } from "unified";
import { describe, expect, it } from "vite-plus/test";
+import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts";
import {
changeRequestReferenceAutolinker,
resolveChangeRequestMediaUrl,
- splitPullRequestBody,
- type PullRequestBodySegment,
-} from "./pullRequestMarkdown.ts";
+} from "./pullRequestReferences.ts";
+
+const definitionParser = unified().use(remarkParse).use(remarkGfm);
+
+// The finder a client passes: each first definition, joined onto one line out of its quote.
+const split = (body: string) =>
+ splitPullRequestBody(body, (markdown) => {
+ const definitions = new Map();
+ const visit = (node: Root | RootContent, quotes: number) => {
+ if (node.type === "definition" && !definitions.has(node.identifier)) {
+ const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
+ const source = markdown.slice(node.position?.start.offset, node.position?.end.offset);
+ definitions.set(node.identifier, source.replace(wrap, " "));
+ }
+ if ("children" in node) {
+ for (const child of node.children)
+ visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
+ }
+ };
+ visit(definitionParser.parse(markdown), 0);
+ return [...definitions.values()];
+ });
describe("pull request body segmentation", () => {
// GitHub writes a dropped image into the body as an ` ` tag, so a bare attachment link on
// its own line is the shape it uses for a video — every one sampled in the wild was one.
it("lifts a dropped video out and keeps the prose around it", () => {
expect(
- splitPullRequestBody(
+ split(
"Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
),
).toEqual([
@@ -43,7 +63,7 @@ describe("pull request body segmentation", () => {
? segment.rows.flat().flatMap((cell) => prose(cell.segments))
: [],
);
- const runs = prose(splitPullRequestBody(body));
+ const runs = prose(split(body));
expect(runs.map((segment) => segment.text)).toEqual([
"- [ ] Before",
" - [ ] code\n- [x] After",
@@ -59,9 +79,7 @@ describe("pull request body segmentation", () => {
it("reads the source out of a video tag, including a multi-line one", () => {
expect(
- splitPullRequestBody(
- '\n \n ',
- ),
+ split('\n \n '),
).toEqual([
{
id: "attachment:0",
@@ -75,21 +93,21 @@ describe("pull request body segmentation", () => {
it("leaves the img tag GitHub writes for a dropped image as markdown", () => {
const body =
' ';
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("never lifts a link inside fenced code out of it", () => {
const body = "```\nhttps://example.com/demo.mp4\n```";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -97,14 +115,14 @@ describe("pull request body segmentation", () => {
// GitHub keeps CRLF in a body written in its web editor.
it("recognizes fences in a body with CRLF line endings", () => {
const body = "```\r\nhttps://example.com/demo.mp4\r\n```";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("closes a CRLF fence, so a video after it still lifts out", () => {
const code = '```html\r\n \r\n```';
- expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
+ expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
{ id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
{
id: "attachment:1",
@@ -117,21 +135,21 @@ describe("pull request body segmentation", () => {
it("does not let a different fence marker close an open fence", () => {
const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("keeps a video tag that shares its line with prose as markdown", () => {
const body = 'Before after';
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("treats an info-string fence as a nested opener, not a close", () => {
const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -139,9 +157,7 @@ describe("pull request body segmentation", () => {
it("does not open a fence on a line of inline triple-backtick code", () => {
const code = "```\nhttps://example.com/b.png\n```";
expect(
- splitPullRequestBody(
- `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`,
- ),
+ split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
).toEqual([
{ id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
{
@@ -153,14 +169,14 @@ describe("pull request body segmentation", () => {
{ id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
]);
const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
- expect(splitPullRequestBody(multilineSpan)).toEqual([
+ expect(split(multilineSpan)).toEqual([
{ id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
]);
});
it("leaves an indented code line alone even when it is only a video link", () => {
const body = " https://example.com/demo.mp4";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -169,14 +185,14 @@ describe("pull request body segmentation", () => {
const body = ['', "still prose", "more prose"].join(
"\n",
);
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
it("refuses a non-http source rather than making a link out of it", () => {
const body = ' ';
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -196,7 +212,7 @@ describe("reference links around lifted media", () => {
);
// Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
const referenceLinks = (body: string) =>
- prose(splitPullRequestBody(body)).flatMap((text) => {
+ prose(split(body)).flatMap((text) => {
const definitions = new Map();
const references: Array<{ identifier: string; text: string }> = [];
const visit = (node: Root | RootContent) => {
@@ -254,7 +270,7 @@ describe("reference links around lifted media", () => {
it("still writes a task tick back to its place in the body", () => {
const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
- const segment = splitPullRequestBody(body).at(-1)!;
+ const segment = split(body).at(-1)!;
if (segment.kind !== "markdown") throw new Error("expected prose last");
const marker = segment.text.indexOf("[ ]");
expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
@@ -267,15 +283,13 @@ describe("media on custom hosts", () => {
["[Recording](https://drop.example.com/recording.mov)", "video"],
["", "image"],
])("recognizes %s without a request", (body, media) => {
- expect(splitPullRequestBody(body)).toEqual([
- expect.objectContaining({ kind: "attachment", media }),
- ]);
+ expect(split(body)).toEqual([expect.objectContaining({ kind: "attachment", media })]);
});
it("keeps inline links and media examples in code as prose", () => {
const body =
"See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -287,7 +301,7 @@ describe("media tables", () => {
const video = "https://example.com/a.mp4";
it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
- const segments = splitPullRequestBody(
+ const segments = split(
`Intro\n\n\nBefore After \n\n\n\n${before}\n\n \n\n\n${after}\n\n \n \n
\n\nOutro`,
);
expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
@@ -313,7 +327,7 @@ describe("media tables", () => {
});
it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
- const [table] = splitPullRequestBody(
+ const [table] = split(
`\nCaption \n\n${video}\n\n \n
`,
);
expect(table).toMatchObject({
@@ -324,7 +338,7 @@ describe("media tables", () => {
it("leaves a table without media links as markdown", () => {
const body = "";
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
]);
});
@@ -356,7 +370,7 @@ describe("media tables", () => {
],
])("splits a media table with %s line by line, as before", (_name, open, close) => {
const body = `${open}\n\n${video}\n\n${close}`;
- expect(splitPullRequestBody(body)).toEqual([
+ expect(split(body)).toEqual([
{ id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
{ id: "attachment:1", kind: "attachment", url: video, media: "video" },
...(close
diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts
index 688235c544fdb..fedbf56fc70dd 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.ts
@@ -1,10 +1,5 @@
-import type { Root, RootContent } from "mdast";
-import remarkGfm from "remark-gfm";
-import remarkParse from "remark-parse";
-import { unified } from "unified";
-
import { GITHUB_EMOJI_ALIASES } from "./githubEmojiAliases.ts";
-import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
+import { sourceControlClients } from "./sourceControlClients.ts";
/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
export type PullRequestBodySegment =
@@ -171,27 +166,6 @@ function mediaTableAt(
return { end, rows: hasMedia ? rows : null };
}
-const definitionParser = unified().use(remarkParse).use(remarkGfm);
-
-/**
- * The first definition of each label in the body, as authored, each joined onto one line so it
- * stands outside the quote or list it was written in.
- */
-function referenceDefinitions(body: string): string[] {
- const definitions = new Map();
- const visit = (node: Root | RootContent, quotes: number) => {
- if (node.type === "definition" && !definitions.has(node.identifier)) {
- const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
- const source = body.slice(node.position?.start.offset, node.position?.end.offset);
- definitions.set(node.identifier, source.replace(wrap, " "));
- }
- if (!("children" in node)) return;
- for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
- };
- visit(definitionParser.parse(body), 0);
- return [...definitions.values()];
-}
-
/**
* Each markdown segment renders as its own document, so it leads with the body's definitions.
* Leading, they win over a later redefinition in the segment, as the first one does in the body.
@@ -220,12 +194,21 @@ function withDefinitions(
};
}
-export function splitPullRequestBody(body: string): ReadonlyArray {
+/**
+ * The first definition of each label in a body, each on one line so it stands outside the quote or
+ * list it was written in, as the client's Markdown parser reads them.
+ */
+export type FindReferenceDefinitions = (body: string) => ReadonlyArray;
+
+export function splitPullRequestBody(
+ body: string,
+ findDefinitions: FindReferenceDefinitions,
+): ReadonlyArray {
const segments = splitBodyAt(body, 0);
// One markdown segment is the whole body, which resolves its own references.
const whole = segments.length === 1 && segments[0]!.kind === "markdown";
if (whole || !body.includes("]:")) return segments;
- const definitions = referenceDefinitions(body);
+ const definitions = findDefinitions(body);
if (definitions.length === 0) return segments;
const leading = `${definitions.join("\n")}\n\n`;
return segments.map((segment) => withDefinitions(segment, leading));
@@ -341,36 +324,6 @@ function splitBodyAt(body: string, baseOffset: number): ReadonlyArray ReadonlyArray) | null {
- if (!changeRequest) return null;
- const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
- const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
- .repositoryUrl;
- return find === undefined || repositoryUrl === undefined
- ? null
- : (text) => find(text, repositoryUrl);
-}
-
-/**
- * Forges link uploads root-relative, as GitCafe's `/api/attachments/`. In a change request
- * body that always means the forge's origin, never a path on the machine rendering it.
- */
-export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: string): string {
- if (!/^\/(?![/\\])/u.test(url)) return url;
- try {
- return new URL(url, changeRequestUrl).href;
- } catch {
- return url;
- }
-}
-
let githubEmojiByAlias: ReadonlyMap | undefined;
const githubEmojiAlias = /:([a-z\d_+-]+)(?=:)/gu;
diff --git a/packages/client-runtime/src/pullRequestReferences.ts b/packages/client-runtime/src/pullRequestReferences.ts
new file mode 100644
index 0000000000000..4195b1feb8c0d
--- /dev/null
+++ b/packages/client-runtime/src/pullRequestReferences.ts
@@ -0,0 +1,30 @@
+import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
+
+/**
+ * Finds the references the change request's host links in plain text, resolved against the change
+ * request's repository. Null when the host links none.
+ */
+export function changeRequestReferenceAutolinker(
+ changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
+): ((text: string) => ReadonlyArray) | null {
+ if (!changeRequest) return null;
+ const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
+ const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
+ .repositoryUrl;
+ return find === undefined || repositoryUrl === undefined
+ ? null
+ : (text) => find(text, repositoryUrl);
+}
+
+/**
+ * Forges link uploads root-relative, as GitCafe's `/api/attachments/`. In a change request
+ * body that always means the forge's origin, never a path on the machine rendering it.
+ */
+export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: string): string {
+ if (!/^\/(?![/\\])/u.test(url)) return url;
+ try {
+ return new URL(url, changeRequestUrl).href;
+ } catch {
+ return url;
+ }
+}
diff --git a/packages/client-runtime/src/skillsLibraryIssues.ts b/packages/client-runtime/src/skillsLibraryIssues.ts
index 4e26dd3b51dd9..ca874da68d761 100644
--- a/packages/client-runtime/src/skillsLibraryIssues.ts
+++ b/packages/client-runtime/src/skillsLibraryIssues.ts
@@ -1,4 +1,6 @@
import type { SkillsLibraryStatus } from "@t3tools/contracts";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
export interface SkillsLibraryIssue {
readonly key: string;
@@ -8,42 +10,65 @@ export interface SkillsLibraryIssue {
readonly guidance: string;
}
-export function skillsLibraryIssues(status: SkillsLibraryStatus): SkillsLibraryIssue[] {
+export function skillsLibraryIssues(
+ status: SkillsLibraryStatus,
+ resolve: MFunctionType = mFallback,
+): SkillsLibraryIssue[] {
return [
...status.conflicts.map((conflict) =>
conflict.reason === "outsideLink"
? {
key: `conflict:${conflict.name}`,
name: conflict.name,
- kind: "Link outside the skill",
+ kind: resolve(msg("Link outside the skill")),
paths: conflict.paths,
- guidance:
- "The second path is a link inside the skill whose target lies outside it. Replace the link with the file before refreshing.",
+ guidance: resolve(
+ msg(
+ "The second path is a link inside the skill whose target lies outside it. Replace the link with the file before refreshing.",
+ ),
+ ),
}
: {
key: `conflict:${conflict.name}`,
name: conflict.name,
- kind: "Copies differ",
+ kind: resolve(msg("Copies differ")),
paths: conflict.paths,
- guidance: "These copies differ. Keep one copy before refreshing.",
+ guidance: resolve(msg("These copies differ. Keep one copy before refreshing.")),
},
),
...status.nameMismatches.map((mismatch) => ({
key: `name:${mismatch.name}`,
name: mismatch.name,
- kind: `Named "${mismatch.frontmatterName}" in SKILL.md`,
+ kind: resolve(msg('Named "{name}" in SKILL.md', { name: mismatch.frontmatterName })),
paths: [],
- guidance: `Some providers use the folder name and others use "${mismatch.frontmatterName}".`,
+ guidance: resolve(
+ msg('Some providers use the folder name and others use "{name}".', {
+ name: mismatch.frontmatterName,
+ }),
+ ),
})),
];
}
-export function skillsLibraryIssueSummary(status: SkillsLibraryStatus): string | null {
- const plural = (count: number, one: string, many: string) =>
- count === 0 ? null : `${count} ${count === 1 ? one : many}`;
+export function skillsLibraryIssueSummary(
+ status: SkillsLibraryStatus,
+ resolve: MFunctionType = mFallback,
+): string | null {
const parts = [
- plural(status.conflicts.length, "conflict", "conflicts"),
- plural(status.nameMismatches.length, "name mismatch", "name mismatches"),
+ status.conflicts.length === 0
+ ? null
+ : resolve(
+ msg("{count, plural, one {{count} conflict} other {{count} conflicts}}", {
+ count: status.conflicts.length,
+ }),
+ ),
+ status.nameMismatches.length === 0
+ ? null
+ : resolve(
+ msg("{count, plural, one {{count} name mismatch} other {{count} name mismatches}}", {
+ count: status.nameMismatches.length,
+ }),
+ ),
].filter((part) => part !== null);
return parts.length === 0 ? null : parts.join(" · ");
}
diff --git a/packages/client-runtime/src/state/inferenceProxy.ts b/packages/client-runtime/src/state/inferenceProxy.ts
index c862c9679b13e..896c96984a42c 100644
--- a/packages/client-runtime/src/state/inferenceProxy.ts
+++ b/packages/client-runtime/src/state/inferenceProxy.ts
@@ -22,6 +22,8 @@ import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { connectionRoutes } from "../connection/routes.ts";
import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
import type { Atom } from "effect/reactivity";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
import { EnvironmentRegistry } from "../connection/registry.ts";
import { requestGuarded } from "../rpc/client.ts";
import { createCommandPermissions } from "./commandPermissions.ts";
@@ -48,6 +50,7 @@ interface EnableInferenceRoutingInput extends InferenceRoutingOptions {
readonly consumer: InferenceConsumer;
readonly driver: InferenceDriver;
readonly environments: ReadonlyArray;
+ readonly resolve?: MFunctionType;
}
export function inferenceHostRoutingIssue(
@@ -57,6 +60,7 @@ export function inferenceHostRoutingIssue(
readonly consumer: InferenceConsumer;
readonly driver: InferenceDriver;
},
+ resolve: MFunctionType = mFallback,
): string | null {
const issue = inferenceRouteIssue(
status,
@@ -65,7 +69,11 @@ export function inferenceHostRoutingIssue(
if (issue !== null) return issue;
return status?.availableDrivers.includes(input.driver)
? null
- : `This host has no available ${INFERENCE_HARNESSES[input.driver].label} accounts.`;
+ : resolve(
+ msg("This host has no available {provider} accounts.", {
+ provider: INFERENCE_HARNESSES[input.driver].label,
+ }),
+ );
}
export function inferenceHostCandidates(
@@ -91,15 +99,18 @@ export function inferenceHostCandidates(
!consumer?.environment.capabilities.inferenceRoutePreservesEnablement
)
return yield* new InferenceProxyError({
- message:
- "Update this environment to reconnect without enabling the provider globally.",
+ message: (input.resolve ?? mFallback)(
+ msg("Update this environment to reconnect without enabling the provider globally."),
+ ),
});
}
const connections = yield* EnvironmentRegistry;
@@ -352,7 +364,7 @@ export function createInferenceProxyAtoms