Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(evals): add contract-aware autocomplete to the code evaluator editor (#14992)

Tobias Wochinger8b146af8b749
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a35b7cb6df..73d81514b7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -435,6 +435,9 @@ importers:
'@baselime/trpc-opentelemetry-middleware':
specifier: ^0.1.2
version: 0.1.2(@opentelemetry/[email protected])(@trpc/[email protected]([email protected]))
+ '@codemirror/autocomplete':
+ specifier: ^6.17.0
+ version: 6.17.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/lang-javascript':
specifier: ^6.2.5
version: 6.2.5
diff --git a/web/package.json b/web/package.json
index 107ec42955..7ea45a811b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -38,6 +38,7 @@
"@aws-crypto/sha256-browser": "^5.2.0",
"@aws-sdk/credential-providers": "catalog:",
"@baselime/trpc-opentelemetry-middleware": "^0.1.2",
+ "@codemirror/autocomplete": "^6.17.0",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
diff --git a/web/src/features/evals/components/code-eval-template-form-body.tsx b/web/src/features/evals/components/code-eval-template-form-body.tsx
index 7f3c1e5203..14ede1660a 100644
--- a/web/src/features/evals/components/code-eval-template-form-body.tsx
+++ b/web/src/features/evals/components/code-eval-template-form-body.tsx
@@ -1,21 +1,35 @@
import CodeMirror, { EditorView, hoverTooltip } from "@uiw/react-codemirror";
import { EditorState, Prec } from "@codemirror/state";
+import { syntaxTree } from "@codemirror/language";
import { linter, type Diagnostic } from "@codemirror/lint";
import { javascript } from "@codemirror/lang-javascript";
import { python } from "@codemirror/lang-python";
import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";
import { useTheme } from "next-themes";
-import { type ReactNode, useCallback, useMemo, useState } from "react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";
import { darkTheme } from "@/src/components/editor/dark-theme";
import { lightTheme } from "@/src/components/editor/light-theme";
+import { autoScrollOnSelectionDrag } from "@/src/components/editor/autoScrollOnSelectionDrag";
import {
getCodeEvalHoverDocs,
+ PROPERTY_ACCESS_ONLY_HOVER_KEYS,
type CodeEvalHoverDocs,
} from "@/src/features/evals/utils/code-eval-template-hover-docs";
+import {
+ getCodeEvalCompletionExtension,
+ isInsideStringOrComment,
+} from "@/src/features/evals/utils/code-eval-template-completions";
import {
formatPythonCodeEvalSourceWithRuff,
type CodeEvalSourceCodeLanguage,
@@ -34,6 +48,22 @@ type CodeEvalTemplateFormBodyProps = {
const FORMAT_SHORTCUT_ARIA = "Alt+Shift+F";
const FUNCTION_CONTRACT_DOCS_URL =
"https://langfuse.com/docs/evaluation/evaluation-methods/code-evaluators#function-contract";
+const CODE_MIRROR_BASIC_SETUP = {
+ autocompletion: false,
+ completionKeymap: false,
+ foldGutter: true,
+ highlightActiveLine: false,
+ lineNumbers: true,
+ searchKeymap: true,
+};
+const codeMirrorLayoutTheme = EditorView.theme({
+ "&.cm-focused": { outline: "none" },
+ ".cm-gutters": { borderRight: "1px solid" },
+ ".cm-scroller": {
+ maxHeight: "60dvh",
+ overflow: "auto",
+ },
+});
function createCodeEvalHoverExtension(hoverDocs: CodeEvalHoverDocs) {
return hoverTooltip((view, pos) => {
@@ -49,6 +79,17 @@ function createCodeEvalHoverExtension(hoverDocs: CodeEvalHoverDocs) {
const from = pos - (before?.length ?? 0);
const to = from + word.length;
+ const node = syntaxTree(view.state).resolveInner(from, 1);
+ if (isInsideStringOrComment(node)) return null;
+ // `type`, `index`, ... are ToolCall properties but also everyday
+ // identifiers; only document them on actual property accesses.
+ if (
+ PROPERTY_ACCESS_ONLY_HOVER_KEYS.has(word) &&
+ node.name !== "PropertyName"
+ ) {
+ return null;
+ }
+
return {
pos: from,
end: to,
@@ -95,36 +136,50 @@ export function CodeEvalTemplateFormBody({
? "Python"
: "TypeScript";
const shouldShowFormatButton = editable;
+ // `onSourceCodeChange` comes from a react-hook-form render prop and changes
+ // identity as the field updates. Keep CodeMirror's handler stable so it does
+ // not reconfigure the editor on every keystroke. The refs are synced in an
+ // effect (not during render) so interrupted concurrent renders never leak.
+ const onSourceCodeChangeRef = useRef(onSourceCodeChange);
+ const sourceCodeRef = useRef(sourceCode);
+ useEffect(() => {
+ onSourceCodeChangeRef.current = onSourceCodeChange;
+ sourceCodeRef.current = sourceCode;
+ });
+ const handleSourceCodeChange = useCallback((value: string) => {
+ sourceCodeRef.current = value;
+ onSourceCodeChangeRef.current(value);
+ }, []);
const diagnostics = useMemo(
() => validationResult?.diagnostics ?? [],
[validationResult?.diagnostics],
);
+ // Reentrancy lives in a ref so `formatSource` (and with it the keydown
+ // extension and the whole extension array) keeps its identity across the
+ // spinner state toggles; `isFormatting` state only drives the button UI.
+ const isFormattingRef = useRef(false);
const formatSource = useCallback(async () => {
- if (!editable || isFormatting) return;
+ if (!editable || isFormattingRef.current) return;
+ isFormattingRef.current = true;
setIsFormatting(true);
try {
const formatted =
sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON
- ? await formatPythonCodeEvalSourceWithRuff(sourceCode)
- : await formatTypeScriptSource(sourceCode);
+ ? await formatPythonCodeEvalSourceWithRuff(sourceCodeRef.current)
+ : await formatTypeScriptSource(sourceCodeRef.current);
// Prettier and Ruff always emit a trailing newline, which CodeMirror
// would render as an empty final line.
- onSourceCodeChange(formatted.trimEnd());
+ handleSourceCodeChange(formatted.trimEnd());
} catch (error) {
console.error(error);
} finally {
+ isFormattingRef.current = false;
setIsFormatting(false);
}
- }, [
- editable,
- isFormatting,
- onSourceCodeChange,
- sourceCode,
- sourceCodeLanguage,
- ]);
+ }, [editable, handleSourceCodeChange, sourceCodeLanguage]);
const linterExtension = useMemo(
() =>
@@ -177,6 +232,34 @@ export function CodeEvalTemplateFormBody({
createCodeEvalHoverExtension(getCodeEvalHoverDocs(sourceCodeLanguage)),
[sourceCodeLanguage],
);
+ const codeEvalCompletionExtension = useMemo(
+ () => getCodeEvalCompletionExtension(sourceCodeLanguage),
+ [sourceCodeLanguage],
+ );
+ const extensions = useMemo(
+ () => [
+ // The `editable` prop only blocks direct typing; readOnly also blocks
+ // paste and drag-and-drop edits.
+ ...(!editable ? [EditorState.readOnly.of(true)] : []),
+ languageExtension,
+ codeEvalCompletionExtension,
+ codeEvalHoverExtension,
+ linterExtension,
+ ...(editable
+ ? [formatShortcutExtension, autoScrollOnSelectionDrag()]
+ : []),
+ EditorView.lineWrapping,
+ codeMirrorLayoutTheme,
+ ],
+ [
+ codeEvalCompletionExtension,
+ codeEvalHoverExtension,
+ editable,
+ formatShortcutExtension,
+ languageExtension,
+ linterExtension,
+ ],
+ );
return (
<div className="space-y-2">
@@ -213,30 +296,10 @@ export function CodeEvalTemplateFormBody({
<CodeMirror
value={sourceCode}
theme={codeMirrorTheme}
- basicSetup={{
- foldGutter: true,
- highlightActiveLine: false,
- lineNumbers: true,
- searchKeymap: true,
- }}
- extensions={[
- ...(!editable ? [EditorState.readOnly.of(true)] : []),
- languageExtension,
- codeEvalHoverExtension,
- linterExtension,
- ...(shouldShowFormatButton ? [formatShortcutExtension] : []),
- EditorView.lineWrapping,
- EditorView.theme({
- "&.cm-focused": { outline: "none" },
- ".cm-gutters": { borderRight: "1px solid" },
- ".cm-scroller": {
- maxHeight: "60dvh",
- overflow: "auto",
- },
- }),
- ]}
+ basicSetup={CODE_MIRROR_BASIC_SETUP}
+ extensions={extensions}
editable={editable}
- onChange={onSourceCodeChange}
+ onChange={handleSourceCodeChange}
className="overflow-hidden rounded-md border text-xs"
/>
<p className="text-muted-foreground text-xs">
diff --git a/web/src/features/evals/utils/code-eval-template-completions.clienttest.ts b/web/src/features/evals/utils/code-eval-template-completions.clienttest.ts
new file mode 100644
index 0000000000..f6c6e87c17
--- /dev/null
+++ b/web/src/features/evals/utils/code-eval-template-completions.clienttest.ts
@@ -0,0 +1,611 @@
+import { EditorState, Transaction } from "@codemirror/state";
+import { acceptCompletion, CompletionContext } from "@codemirror/autocomplete";
+import { javascript } from "@codemirror/lang-javascript";
+import { python } from "@codemirror/lang-python";
+import { basicSetup, EditorView } from "@uiw/react-codemirror";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+import {
+ getCodeEvalCompletionExtension,
+ getCodeEvalCompletionSource,
+} from "@/src/features/evals/utils/code-eval-template-completions";
+import {
+ CODE_EVAL_COMPLETION_CONTRACT,
+ type CodeEvalSourceCodeLanguage,
+} from "@/src/features/evals/utils/code-eval-template-starter-examples";
+
+const originalGetClientRects = Range.prototype.getClientRects;
+
+beforeAll(() => {
+ Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
+});
+
+afterAll(() => {
+ Range.prototype.getClientRects = originalGetClientRects;
+});
+
+const TOOL_CALL_LABELS = ["id", "name", "arguments", "type", "index"];
+
+function languageExtensionFor(sourceCodeLanguage: CodeEvalSourceCodeLanguage) {
+ return sourceCodeLanguage === "PYTHON"
+ ? python()
+ : javascript({ typescript: true });
+}
+
+function getCompletions(
+ doc: string,
+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,
+) {
+ const result = runCompletionSource(doc, sourceCodeLanguage);
+
+ return {
+ from: result?.from,
+ labels: result?.options.map((option) => option.label),
+ acceptsEmptyPrefix:
+ result?.validFor instanceof RegExp ? result.validFor.test("") : false,
+ };
+}
+
+function runCompletionSource(
+ doc: string,
+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,
+ position = doc.length,
+) {
+ const state = EditorState.create({
+ doc,
+ extensions: [languageExtensionFor(sourceCodeLanguage)],
+ });
+ const source = getCodeEvalCompletionSource(sourceCodeLanguage);
+ return source(new CompletionContext(state, position, false));
+}
+
+function mountEditor(
+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,
+ options: { doc?: string; anchor?: number } = {},
+) {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ const view = new EditorView({
+ parent,
+ state: EditorState.create({
+ doc: options.doc,
+ selection:
+ options.anchor !== undefined ? { anchor: options.anchor } : undefined,
+ extensions: [
+ basicSetup({ autocompletion: false, completionKeymap: false }),
+ languageExtensionFor(sourceCodeLanguage),
+ getCodeEvalCompletionExtension(sourceCodeLanguage),
+ ],
+ }),
+ });
+
+ return {
+ view,
+ typeText: (from: number, insert: string, anchor: number) =>
+ view.dispatch({
+ changes: { from, insert },
+ selection: { anchor },
+ annotations: Transaction.userEvent.of("input.type"),
+ }),
+ completionLabels: () =>
+ Array.from(
+ parent.querySelectorAll<HTMLElement>(".cm-completionLabel"),
+ ).map((element) => element.textContent),
+ cleanup: () => {
+ view.destroy();
+ parent.remove();
+ },
+ };
+}
+
+describe("code evaluator context completions", () => {
+ it.each(["TYPESCRIPT", "PYTHON"] as const)(
+ "opens automatically while typing in %s",
+ async (sourceCodeLanguage) => {
+ const editor = mountEditor(sourceCodeLanguage);
+
+ try {
+ editor.typeText(0, "ctx.", 4);
+
+ await vi.waitFor(() => {
+ expect(editor.completionLabels()).toEqual(
+ expect.arrayContaining(["observation", "experiment"]),
+ );
+ expect(editor.completionLabels()).toHaveLength(2);
+ });
+ } finally {
+ editor.cleanup();
+ }
+ },
+ );
+
+ it("chains TypeScript dataType property and enum completions", async () => {
+ const editor = mountEditor("TYPESCRIPT");
+
+ try {
+ const source =
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ dataT";
+ editor.typeText(0, source, source.length);
+
+ await vi.waitFor(() => {
+ expect(editor.completionLabels()).toEqual(["dataType"]);
+ });
+ // @codemirror/autocomplete guards acceptCompletion behind a ~75ms
+ // interaction delay after the popup opens.
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(acceptCompletion(editor.view)).toBe(true);
+
+ await vi.waitFor(() => {
+ expect(editor.completionLabels()).toEqual(
+ expect.arrayContaining([
+ '"NUMERIC"',
+ '"BOOLEAN"',
+ '"CATEGORICAL"',
+ '"TEXT"',
+ ]),
+ );
+ expect(editor.completionLabels()).toHaveLength(4);
+ });
+ } finally {
+ editor.cleanup();
+ }
+ });
+
+ it("completes the documented TypeScript context tree", () => {
+ expect(getCompletions("ctx.", "TYPESCRIPT")).toEqual({
+ from: 4,
+ labels: ["observation", "experiment"],
+ acceptsEmptyPrefix: true,
+ });
+ expect(getCompletions("ctx.observation.", "TYPESCRIPT")).toEqual({
+ from: 16,
+ labels: ["input", "output", "metadata", "toolCalls"],
+ acceptsEmptyPrefix: true,
+ });
+ expect(getCompletions("ctx.experiment?.", "TYPESCRIPT")).toEqual({
+ from: 16,
+ labels: ["itemExpectedOutput", "itemMetadata"],
+ acceptsEmptyPrefix: true,
+ });
+ });
+
+ it("completes the documented Python context tree", () => {
+ expect(getCompletions("ctx.", "PYTHON")).toEqual({
+ from: 4,
+ labels: ["observation", "experiment"],
+ acceptsEmptyPrefix: true,
+ });
+ expect(getCompletions("ctx.observation.", "PYTHON")).toEqual({
+ from: 16,
+ labels: ["input", "output", "metadata", "tool_calls"],
+ acceptsEmptyPrefix: true,
+ });
+ expect(getCompletions("ctx.experiment.", "PYTHON")).toEqual({
+ from: 15,
+ labels: ["item_expected_output", "item_metadata"],
+ acceptsEmptyPrefix: true,
+ });
+ });
+
+ it("completes fields on indexed tool calls", () => {
+ expect(
+ getCompletions("ctx.observation.toolCalls[callIndex]?.", "TYPESCRIPT"),
+ ).toEqual({
+ from: 38,
+ labels: TOOL_CALL_LABELS,
+ acceptsEmptyPrefix: true,
+ });
+ expect(
+ getCompletions("ctx.observation.toolCalls?.[0].", "TYPESCRIPT"),
+ ).toEqual({
+ from: 31,
+ labels: TOOL_CALL_LABELS,
+ acceptsEmptyPrefix: true,
+ });
+ expect(
+ getCompletions("ctx.observation.tool_calls[-1].na", "PYTHON"),
+ ).toEqual({
+ from: 31,
+ labels: TOOL_CALL_LABELS,
+ acceptsEmptyPrefix: true,
+ });
+ });
+
+ it("completes while editing inside an identifier", () => {
+ const midWord = runCompletionSource("ctx.observation", "TYPESCRIPT", 8);
+ expect(midWord?.from).toBe(4);
+ expect(midWord?.options.map((option) => option.label)).toEqual([
+ "observation",
+ "experiment",
+ ]);
+
+ // The keyword argument being edited keeps its own name available.
+ const editedKeyword = runCompletionSource(
+ "return Score(name=1)",
+ "PYTHON",
+ "return Score(na".length,
+ );
+ expect(editedKeyword?.from).toBe("return Score(".length);
+ expect(editedKeyword?.options.map((option) => option.label)).toContain(
+ "name",
+ );
+ });
+
+ it("follows direct and chained context aliases", () => {
+ expect(
+ getCompletions(
+ "function evaluate(ctx) {\n const observation = ctx.observation;\n const alias = observation;\n alias.to",
+ "TYPESCRIPT",
+ ),
+ ).toEqual({
+ from: 101,
+ labels: ["input", "output", "metadata", "toolCalls"],
+ acceptsEmptyPrefix: true,
+ });
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n alias = observation\n alias.to",
+ "PYTHON",
+ ),
+ ).toEqual({
+ from: 81,
+ labels: ["input", "output", "metadata", "tool_calls"],
+ acceptsEmptyPrefix: true,
+ });
+ });
+
+ it("stops completing aliases after reassignment", () => {
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n observation = {}\n observation.",
+ "PYTHON",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n if ctx.observation.input:\n observation = {}\n observation.",
+ "PYTHON",
+ ).labels,
+ ).toBeUndefined();
+ });
+
+ it("completes inside string interpolations", () => {
+ const templateString = "`${ctx.observation.}`";
+ expect(
+ runCompletionSource(
+ templateString,
+ "TYPESCRIPT",
+ templateString.indexOf(".}") + 1,
+ )?.options.map((option) => option.label),
+ ).toEqual(["input", "output", "metadata", "toolCalls"]);
+
+ const formatString = 'f"{ctx.observation.}"';
+ expect(
+ runCompletionSource(
+ formatString,
+ "PYTHON",
+ formatString.indexOf(".}") + 1,
+ )?.options.map((option) => option.label),
+ ).toEqual(["input", "output", "metadata", "tool_calls"]);
+ });
+
+ it("invalidates aliases shadowed by loop, catch, and with bindings", () => {
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n for observation in items:\n observation.",
+ "PYTHON",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ "function evaluate(ctx) {\n const observation = ctx.observation;\n for (const observation of items) {\n observation.",
+ "TYPESCRIPT",
+ ).labels,
+ ).toBeUndefined();
+ // The iterated expression is a read, not a binding.
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n for item in observation.tool_calls:\n pass\n observation.",
+ "PYTHON",
+ ).labels,
+ ).toEqual(["input", "output", "metadata", "tool_calls"]);
+ });
+
+ it("invalidates aliases behind tuple, destructuring, and multi-declarator targets", () => {
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n b = ctx.observation\n a, b = 1, 2\n b.",
+ "PYTHON",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ "function evaluate(ctx) {\n let x = ctx.observation;\n [x] = [{}];\n x.",
+ "TYPESCRIPT",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ "function evaluate(ctx) {\n var x = ctx.observation;\n var a = 1, x = {};\n x.",
+ "TYPESCRIPT",
+ ).labels,
+ ).toBeUndefined();
+ });
+
+ it("keeps aliases that are only written through member targets", () => {
+ expect(
+ getCompletions(
+ "def evaluate(ctx):\n observation = ctx.observation\n cache[0] = observation\n observation.",
+ "PYTHON",
+ ).labels,
+ ).toEqual(["input", "output", "metadata", "tool_calls"]);
+ expect(
+ getCompletions(
+ "function evaluate(ctx) {\n const observation = ctx.observation;\n cache[0] = observation;\n observation.",
+ "TYPESCRIPT",
+ ).labels,
+ ).toEqual(["input", "output", "metadata", "toolCalls"]);
+ });
+
+ it("completes Python result constructors and unused keyword parameters", () => {
+ const pythonContract = CODE_EVAL_COMPLETION_CONTRACT.PYTHON;
+
+ expect(getCompletions("return Eval", "PYTHON").labels).toEqual([
+ "EvaluationResult",
+ "Score",
+ ]);
+
+ const evaluationResult = runCompletionSource(
+ "return EvaluationResult(sc",
+ "PYTHON",
+ );
+ expect(evaluationResult?.options).toEqual(
+ pythonContract.constructorParameters.EvaluationResult.map(
+ (parameter) => ({
+ ...parameter,
+ type: "property",
+ apply: `${parameter.label}=`,
+ }),
+ ),
+ );
+
+ const score = runCompletionSource(
+ 'return Score(name="quality", va',
+ "PYTHON",
+ );
+ expect(score?.options).toEqual(
+ pythonContract.constructorParameters.Score.filter(
+ (parameter) => parameter.label !== "name",
+ ).map((parameter) => ({
+ ...parameter,
+ type: "property",
+ apply: `${parameter.label}=`,
+ })),
+ );
+ });
+
+ it("completes the TypeScript return type and returned object fields", () => {
+ const typescriptContract = CODE_EVAL_COMPLETION_CONTRACT.TYPESCRIPT;
+
+ const returnType = runCompletionSource(
+ "function evaluate(ctx: EvaluationContext): Eval",
+ "TYPESCRIPT",
+ );
+ expect(returnType?.options).toEqual([
+ { ...typescriptContract.resultType, type: "type" },
+ ]);
+ expect(
+ runCompletionSource(
+ "async function evaluate(ctx: EvaluationContext): Promise<Eval",
+ "TYPESCRIPT",
+ )?.options,
+ ).toEqual([{ ...typescriptContract.resultType, type: "type" }]);
+
+ const result = runCompletionSource(
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { sc",
+ "TYPESCRIPT",
+ );
+ expect(result?.options).toEqual(
+ typescriptContract.resultProperties.map((property) => ({
+ ...property,
+ type: "property",
+ apply: `${property.label}: `,
+ })),
+ );
+
+ const score = runCompletionSource(
+ 'function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ name: "quality", va',
+ "TYPESCRIPT",
+ );
+ expect(score?.options).toEqual(
+ typescriptContract.scoreProperties
+ .filter((property) => property.label !== "name")
+ .map((property) => ({
+ ...property,
+ type: "property",
+ apply: `${property.label}: `,
+ })),
+ );
+ });
+
+ it("keeps offering entry completions after whitespace behind `{`, `(`, or `,`", () => {
+ const scoreObjectPrefix =
+ 'function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ comment: "quality",';
+
+ for (const doc of [`${scoreObjectPrefix} `, `${scoreObjectPrefix}\n `]) {
+ expect(
+ runCompletionSource(doc, "TYPESCRIPT")?.options.map(
+ (option) => option.label,
+ ),
+ ).toEqual(["name", "value", "dataType", "configId", "metadata"]);
+ }
+ expect(
+ runCompletionSource(
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { ",
+ "TYPESCRIPT",
+ )?.options.map((option) => option.label),
+ ).toEqual(["scores"]);
+ expect(
+ runCompletionSource(
+ 'return Score(name="quality", ',
+ "PYTHON",
+ )?.options.map((option) => option.label),
+ ).toEqual(["value", "data_type", "comment", "config_id", "metadata"]);
+
+ // After a value without a separator, inserting a property would be
+ // invalid syntax.
+ expect(
+ getCompletions(
+ 'function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ comment: "quality" ',
+ "TYPESCRIPT",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions('return Score(name="quality" ', "PYTHON").labels,
+ ).toBeUndefined();
+ });
+
+ it("keeps the completion popup open when typing a space after a comma", async () => {
+ const editor = mountEditor("TYPESCRIPT");
+
+ try {
+ const source =
+ 'function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ comment: "quality",';
+ editor.typeText(0, source, source.length);
+
+ await vi.waitFor(() => {
+ expect(editor.completionLabels()).toContain("name");
+ });
+
+ editor.typeText(source.length, " ", source.length + 1);
+
+ await vi.waitFor(() => {
+ expect(editor.completionLabels()).toContain("name");
+ });
+ } finally {
+ editor.cleanup();
+ }
+ });
+
+ it("treats arrow-function evaluators like function declarations", () => {
+ expect(
+ runCompletionSource(
+ "const evaluate = (ctx: EvaluationContext): Eval",
+ "TYPESCRIPT",
+ )?.options.map((option) => option.label),
+ ).toEqual(["EvaluationResult"]);
+ expect(
+ runCompletionSource(
+ "const evaluate = (ctx: EvaluationContext): EvaluationResult => { return { sc",
+ "TYPESCRIPT",
+ )?.options.map((option) => option.label),
+ ).toEqual(["scores"]);
+ // Expression bodies return without a ReturnStatement. Brackets are
+ // balanced because closeBrackets auto-inserts them while typing.
+ const expressionBody =
+ "const evaluate = (ctx: EvaluationContext): EvaluationResult => ({ sc })";
+ expect(
+ runCompletionSource(
+ expressionBody,
+ "TYPESCRIPT",
+ expressionBody.indexOf("sc ") + 2,
+ )?.options.map((option) => option.label),
+ ).toEqual(["scores"]);
+
+ // Only the evaluator's declarator counts.
+ const otherExpressionBody =
+ "const other = (ctx: EvaluationContext): EvaluationResult => ({ sc })";
+ expect(
+ runCompletionSource(
+ otherExpressionBody,
+ "TYPESCRIPT",
+ otherExpressionBody.indexOf("sc ") + 2,
+ ),
+ ).toBeNull();
+ });
+
+ it("completes TypeScript score data type values inside strings", () => {
+ const scorePrefix =
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ dataType: ";
+
+ expect(getCompletions(scorePrefix, "TYPESCRIPT").labels).toEqual([
+ '"NUMERIC"',
+ '"BOOLEAN"',
+ '"CATEGORICAL"',
+ '"TEXT"',
+ ]);
+ expect(getCompletions(`${scorePrefix}"BO`, "TYPESCRIPT").labels).toEqual([
+ '"NUMERIC"',
+ '"BOOLEAN"',
+ '"CATEGORICAL"',
+ '"TEXT"',
+ ]);
+ expect(getCompletions(`${scorePrefix}'CA`, "TYPESCRIPT").labels).toEqual([
+ "'NUMERIC'",
+ "'BOOLEAN'",
+ "'CATEGORICAL'",
+ "'TEXT'",
+ ]);
+
+ const completeSource = `${scorePrefix}"" }] }; }`;
+ expect(
+ runCompletionSource(
+ completeSource,
+ "TYPESCRIPT",
+ completeSource.indexOf('""') + 1,
+ )?.options.map((option) => option.label),
+ ).toEqual(['"NUMERIC"', '"BOOLEAN"', '"CATEGORICAL"', '"TEXT"']);
+
+ // Accepting mid-value replaces the whole quoted value so no suffix of the
+ // old value survives ("CA|TEGORY" must not become "NUMERICTEGORY").
+ const midValueSource = `${scorePrefix}"CATEGORY" }] }; }`;
+ const midValue = runCompletionSource(
+ midValueSource,
+ "TYPESCRIPT",
+ midValueSource.indexOf('"CATEGORY') + 3,
+ );
+ expect(midValue?.to).toBe(
+ midValueSource.indexOf('"CATEGORY') + '"CATEGORY'.length,
+ );
+ });
+
+ it("completes Python score data type values before typing a value", () => {
+ // Quote-variant handling is shared code covered by the TypeScript test.
+ expect(
+ getCompletions(
+ 'return Score(name="quality", value=True, data_type=',
+ "PYTHON",
+ ).labels,
+ ).toEqual(['"NUMERIC"', '"BOOLEAN"', '"CATEGORICAL"', '"TEXT"']);
+ });
+
+ it("does not complete unrelated paths, strings, comments, or prototypes", () => {
+ expect(getCompletions("other.observation.", "TYPESCRIPT").labels).toBe(
+ undefined,
+ );
+ expect(
+ getCompletions('"ctx.observation.toolCalls[0]."', "TYPESCRIPT").labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions("# ctx.observation.tool_calls[0].", "PYTHON").labels,
+ ).toBeUndefined();
+ expect(getCompletions("ctx.", "TYPESCRIPT").labels).not.toContain(
+ "toString",
+ );
+ expect(
+ getCompletions("const unrelated = { sc", "TYPESCRIPT").labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [{ dataType: // BOOLEAN",
+ "TYPESCRIPT",
+ ).labels,
+ ).toBeUndefined();
+ expect(
+ getCompletions(
+ 'return Score(name="quality", value=True, data_type= # BOOLEAN',
+ "PYTHON",
+ ).labels,
+ ).toBeUndefined();
+ });
+});
diff --git a/web/src/features/evals/utils/code-eval-template-completions.ts b/web/src/features/evals/utils/code-eval-template-completions.ts
new file mode 100644
index 0000000000..04284ead90
--- /dev/null
+++ b/web/src/features/evals/utils/code-eval-template-completions.ts
@@ -0,0 +1,977 @@
+import {
+ autocompletion,
+ type Completion,
+ type CompletionContext,
+ type CompletionResult,
+ type CompletionSource,
+} from "@codemirror/autocomplete";
+import { javascriptLanguage } from "@codemirror/lang-javascript";
+import { pythonLanguage } from "@codemirror/lang-python";
+import { syntaxTree } from "@codemirror/language";
+
+import {
+ CODE_EVAL_COMPLETION_CONTRACT,
+ type CodeEvalSourceCodeLanguage,
+} from "@/src/features/evals/utils/code-eval-template-starter-examples";
+
+// Member paths are read from the syntax tree by hand: lang-javascript's
+// `completionPath` cannot express indexed access (`toolCalls[0].`) and
+// lang-python has no equivalent. One implementation covers both languages
+// because lezer-python emits the same MemberExpression / PropertyName /
+// VariableName node names as lezer-javascript.
+
+type SyntaxNode = ReturnType<typeof syntaxTree>["topNode"];
+
+type CompletionHandler = (
+ context: CompletionContext,
+ inner: SyntaxNode,
+) => CompletionResult | null;
+
+const propertyOptions = (
+ properties: readonly { label: string; detail: string }[],
+) => properties.map((property) => ({ ...property, type: "property" }));
+
+const TYPESCRIPT_CONTRACT = CODE_EVAL_COMPLETION_CONTRACT.TYPESCRIPT;
+const PYTHON_CONTRACT = CODE_EVAL_COMPLETION_CONTRACT.PYTHON;
+
+const INDEX_PATH_SEGMENT = "[]";
+
+function buildPathCompletions(
+ pathProperties: Record<string, readonly { label: string; detail: string }[]>,
+ toolCallProperties: readonly { label: string; detail: string }[],
+ toolCallsPath: string,
+) {
+ const pathCompletions = new Map(
+ Object.entries(pathProperties).map(
+ ([path, properties]) => [path, propertyOptions(properties)] as const,
+ ),
+ );
+ // Indexed element access completes the element type's properties.
+ pathCompletions.set(
+ `${toolCallsPath}.${INDEX_PATH_SEGMENT}`,
+ propertyOptions(toolCallProperties),
+ );
+ return pathCompletions;
+}
+
+const TYPESCRIPT_EVALUATION_RESULT = {
+ ...TYPESCRIPT_CONTRACT.resultType,
+ type: "type",
+} as const;
+
+const PYTHON_RESULT_CONSTRUCTORS = PYTHON_CONTRACT.resultConstructors.map(
+ (constructor) => ({ ...constructor, type: "class" }),
+);
+
+const PYTHON_CONSTRUCTOR_PARAMETERS = new Map<
+ string,
+ readonly { label: string; detail: string }[]
+>(Object.entries(PYTHON_CONTRACT.constructorParameters));
+
+const ENUM_VALUE_PROPERTIES = new Set(["dataType", "data_type"]);
+
+const OBJECT_NODES = new Set(["ObjectExpression", "ObjectPattern"]);
+const ARRAY_NODES = new Set(["ArrayExpression", "ArrayPattern"]);
+const EXPRESSION_WRAPPER_NODES = new Set([
+ "AssignmentExpression",
+ "ParenthesizedExpression",
+]);
+
+const SCOPE_NODES = new Set([
+ "FunctionDeclaration",
+ "FunctionExpression",
+ "ArrowFunction",
+ "FunctionDefinition",
+]);
+
+const NESTED_SCOPE_NODES = new Set([
+ ...SCOPE_NODES,
+ "ClassDeclaration",
+ "ClassDefinition",
+]);
+
+const CONTROL_FLOW_NODES = new Set([
+ "Block",
+ "Body",
+ "IfStatement",
+ "ForStatement",
+ "WhileStatement",
+ "TryStatement",
+ "MatchStatement",
+ "SwitchStatement",
+]);
+
+const STRING_AND_COMMENT_SYNTAX_NODES: ReadonlySet<string> = new Set([
+ "String",
+ "FormatString",
+ "TemplateString",
+ "Comment",
+ "LineComment",
+ "BlockComment",
+]);
+const DATA_TYPE_IGNORED_SYNTAX_NODES: ReadonlySet<string> = new Set(
+ [...STRING_AND_COMMENT_SYNTAX_NODES].filter((node) => node !== "String"),
+);
+// `${…}` / f"{…}" interpolations embed real code inside string literals.
+const INTERPOLATION_NODES = new Set(["Interpolation", "FormatReplacement"]);
+
+export function isInsideStringOrComment(node: SyntaxNode) {
+ for (
+ let ancestor: SyntaxNode | null = node;
+ ancestor;
+ ancestor = ancestor.parent
+ ) {
+ if (INTERPOLATION_NODES.has(ancestor.name)) return false;
+ if (STRING_AND_COMMENT_SYNTAX_NODES.has(ancestor.name)) return true;
+ }
+ return false;
+}
+
+const TYPESCRIPT_PROPERTY_NAME = /^(?:[$A-Za-z_][$A-Za-z0-9_]*)?$/;
+const PYTHON_PROPERTY_NAME = /^(?:[A-Za-z_][A-Za-z0-9_]*)?$/;
+
+function sliceNode(context: CompletionContext, node: SyntaxNode) {
+ return context.state.doc.sliceString(node.from, node.to);
+}
+
+// Slice an identifier only up to the cursor so completing mid-word filters and
+// replaces the typed prefix (`ctx.obse|rvation`), not text after the cursor.
+function sliceNameToCursor(context: CompletionContext, node: SyntaxNode) {
+ return context.state.doc.sliceString(
+ node.from,
+ Math.min(node.to, context.pos),
+ );
+}
+
+function readMemberPath(
+ node: SyntaxNode,
+ context: CompletionContext,
+): string[] | null {
+ if (node.name === "VariableName") {
+ return [sliceNode(context, node)];
+ }
+ if (node.name !== "MemberExpression") return null;
+
+ const object = node.firstChild;
+ const operator = object?.nextSibling;
+ if (!object || !operator) return null;
+
+ const path = readMemberPath(object, context);
+ if (!path) return null;
+
+ if (
+ operator.name === "[" ||
+ (operator.name === "?." && operator.nextSibling?.name === "[")
+ ) {
+ return node.lastChild?.name === "]" ? [...path, INDEX_PATH_SEGMENT] : null;
+ }
+
+ const property = operator.nextSibling;
+ if (
+ (operator.name !== "." && operator.name !== "?.") ||
+ property?.name !== "PropertyName"
+ ) {
+ return null;
+ }
+
+ return [...path, sliceNode(context, property)];
+}
+
+function resolveContractPath(
+ path: string[],
+ aliases: ReadonlyMap<string, string[]>,
+) {
+ if (path[0] === "ctx") return path;
+
+ const aliasPath = aliases.get(path[0] ?? "");
+ return aliasPath ? [...aliasPath, ...path.slice(1)] : null;
+}
+
+function nodeKey(node: SyntaxNode) {
+ return `${node.name}:${node.from}:${node.to}`;
+}
+
+function getCompletionScope(inner: SyntaxNode) {
+ let top = inner;
+ for (let node: SyntaxNode | null = inner; node; node = node.parent) {
+ if (SCOPE_NODES.has(node.name)) return node;
+ top = node;
+ }
+ return top;
+}
+
+const ASSIGNMENT_NODES = new Set([
+ "VariableDeclaration", // TS `let x = …`, possibly with several declarators
+ "AssignmentExpression", // TS `x = …`, `[x] = …`, `x += …`
+ "AssignStatement", // PY `x = …`, `a, b = …`, `x = y = …`
+ "UpdateStatement", // PY `x += …`
+]);
+const ASSIGNMENT_OPERATOR_NODES = new Set(["Equals", "AssignOp"]);
+// Destructuring containers whose variable names an assignment rebinds. Member
+// targets (`cache[0] = …`) rebind no variable and must not appear here.
+const BINDING_PATTERN_NODES = new Set([
+ "ArrayPattern",
+ "ObjectPattern",
+ "PatternProperty",
+ "ParenthesizedExpression",
+ "TupleExpression",
+]);
+
+function collectTargetNames(
+ node: SyntaxNode,
+ context: CompletionContext,
+ into: string[],
+) {
+ if (node.name === "VariableName" || node.name === "VariableDefinition") {
+ into.push(sliceNode(context, node));
+ return;
+ }
+ if (BINDING_PATTERN_NODES.has(node.name)) {
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ collectTargetNames(child, context, into);
+ }
+ }
+}
+
+type AssignmentTarget = {
+ name: string;
+ // Set only when this name is the sole, plain-variable target of its
+ // assignment: anything else (tuples, patterns, `+=`) cannot alias safely.
+ value: SyntaxNode | null;
+};
+
+function readDeclarationTargets(
+ node: SyntaxNode,
+ context: CompletionContext,
+): AssignmentTarget[] {
+ const targets: AssignmentTarget[] = [];
+ let pendingSimple: SyntaxNode | null = null;
+ let pendingPatternNames: string[] = [];
+
+ const flush = (value: SyntaxNode | null) => {
+ if (pendingSimple) {
+ targets.push({ name: sliceNode(context, pendingSimple), value });
+ }
+ for (const name of pendingPatternNames) targets.push({ name, value: null });
+ pendingSimple = null;
+ pendingPatternNames = [];
+ };
+
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (child.name === "VariableDefinition") {
+ pendingSimple = child;
+ } else if (BINDING_PATTERN_NODES.has(child.name)) {
+ collectTargetNames(child, context, pendingPatternNames);
+ } else if (ASSIGNMENT_OPERATOR_NODES.has(child.name)) {
+ flush(child.nextSibling);
+ } else if (child.name === ",") {
+ // Declarator without initializer (`let x, y = 1`) still rebinds x.
+ flush(null);
+ }
+ }
+ flush(null);
+ return targets;
+}
+
+function readAssignmentTargets(
+ node: SyntaxNode,
+ context: CompletionContext,
+): AssignmentTarget[] {
+ if (node.name === "VariableDeclaration") {
+ return readDeclarationTargets(node, context);
+ }
+
+ // Split children into sections separated by assignment operators: the last
+ // section is the assigned value, every earlier one a target list (chained
+ // `x = y = …` has several target sections).
+ const sections: SyntaxNode[][] = [[]];
+ let aliasBlocked = false;
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (ASSIGNMENT_OPERATOR_NODES.has(child.name)) {
+ sections.push([]);
+ } else if (child.name === "UpdateOp") {
+ // Augmented assignment (`x += …`) rebinds x to a derived value.
+ aliasBlocked = true;
+ sections.push([]);
+ } else if (child.name !== ",") {
+ sections[sections.length - 1].push(child);
+ }
+ }
+ if (sections.length === 1) {
+ // Operator not recognized (`x ??= …`): invalidate anything that looks
+ // like a target rather than risking a stale alias.
+ const names: string[] = [];
+ for (const part of sections[0]) collectTargetNames(part, context, names);
+ return names.map((name) => ({ name, value: null }));
+ }
+
+ const valueSection = sections.pop() ?? [];
+ const value =
+ !aliasBlocked && valueSection.length === 1 ? valueSection[0] : null;
+
+ const targets: AssignmentTarget[] = [];
+ for (const section of sections) {
+ const [first] = section;
+ if (
+ section.length === 1 &&
+ (first.name === "VariableName" || first.name === "VariableDefinition")
+ ) {
+ targets.push({ name: sliceNode(context, first), value });
+ continue;
+ }
+ const names: string[] = [];
+ for (const part of section) collectTargetNames(part, context, names);
+ for (const name of names) targets.push({ name, value: null });
+ }
+ return targets;
+}
+
+// Constructs that rebind names without an assignment node. "ForStatement" and
+// "TryStatement" match both grammars; the TS variants keep their targets in
+// ForOfSpec/ForInSpec/CatchClause children, so the flat rules find nothing.
+const BINDING_NODES = new Set([
+ "ForOfSpec",
+ "ForInSpec",
+ "CatchClause",
+ "ForStatement",
+ "WithStatement",
+ "TryStatement",
+]);
+
+function readBindingTargetNames(node: SyntaxNode, context: CompletionContext) {
+ const names: string[] = [];
+
+ if (
+ node.name === "ForOfSpec" ||
+ node.name === "ForInSpec" ||
+ node.name === "CatchClause"
+ ) {
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (
+ child.name === "of" ||
+ child.name === "in" ||
+ child.name === "Block"
+ ) {
+ break;
+ }
+ collectTargetNames(child, context, names);
+ }
+ return names;
+ }
+
+ if (node.name === "ForStatement") {
+ // PY `for x in items:` — everything after `in` is a read, not a target.
+ for (
+ let child = node.firstChild;
+ child && child.name !== "in";
+ child = child.nextSibling
+ ) {
+ collectTargetNames(child, context, names);
+ }
+ return names;
+ }
+
+ // PY WithStatement / TryStatement: only the name directly after `as` is
+ // bound (`except ValueError as e:` reads ValueError, binds e).
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (child.name === "as" && child.nextSibling?.name === "VariableName") {
+ names.push(sliceNode(context, child.nextSibling));
+ }
+ }
+ return names;
+}
+
+function isOnCursorPath(
+ node: SyntaxNode,
+ scope: SyntaxNode,
+ cursorAncestors: ReadonlySet<string>,
+) {
+ // An assignment in another branch may not run, so it invalidates rather
+ // than establishes an alias for code at the cursor.
+ for (
+ let parent = node.parent;
+ parent && parent !== scope;
+ parent = parent.parent
+ ) {
+ if (
+ CONTROL_FLOW_NODES.has(parent.name) &&
+ !cursorAncestors.has(nodeKey(parent))
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function getContractAliases(context: CompletionContext, inner: SyntaxNode) {
+ const aliases = new Map<string, string[]>();
+ const scope = getCompletionScope(inner);
+ const cursorAncestors = new Set<string>();
+
+ for (let node: SyntaxNode | null = inner; node; node = node.parent) {
+ cursorAncestors.add(nodeKey(node));
+ if (node.from === scope.from && node.to === scope.to) break;
+ }
+
+ function visit(node: SyntaxNode) {
+ if (node.from >= context.pos) return;
+ if (node !== scope && NESTED_SCOPE_NODES.has(node.name)) return;
+
+ // Bindings shadow for their whole statement (the cursor may sit inside
+ // the loop body), so invalidate regardless of where the node ends.
+ if (BINDING_NODES.has(node.name)) {
+ for (const name of readBindingTargetNames(node, context)) {
+ aliases.delete(name);
+ }
+ }
+
+ if (ASSIGNMENT_NODES.has(node.name) && node.to <= context.pos) {
+ const allowAlias = isOnCursorPath(node, scope, cursorAncestors);
+ for (const target of readAssignmentTargets(node, context)) {
+ const path =
+ allowAlias && target.value
+ ? readMemberPath(target.value, context)
+ : null;
+ const resolvedPath = path ? resolveContractPath(path, aliases) : null;
+
+ if (resolvedPath) aliases.set(target.name, resolvedPath);
+ else aliases.delete(target.name);
+ }
+ // Keep descending: the assigned value can nest further assignments
+ // (`cache[0] = x = {}` must still invalidate `x`).
+ }
+
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ visit(child);
+ }
+ }
+
+ visit(scope);
+ return aliases;
+}
+
+function getSyntaxCompletionPath(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let member: SyntaxNode | null = null;
+ let name = "";
+
+ if (inner.name === "PropertyName") {
+ member = inner.parent;
+ name = sliceNameToCursor(context, inner);
+ } else if (
+ (inner.name === "." || inner.name === "?.") &&
+ inner.parent?.name === "MemberExpression"
+ ) {
+ member = inner.parent;
+ } else if (inner.name === "MemberExpression") {
+ member = inner;
+ }
+
+ const object = member?.firstChild;
+ const path = object ? readMemberPath(object, context) : null;
+ if (!path) return null;
+
+ const resolvedPath = resolveContractPath(
+ path,
+ path[0] === "ctx" ? new Map() : getContractAliases(context, inner),
+ );
+ return resolvedPath ? { path: resolvedPath, name } : null;
+}
+
+// Whitespace after `{`, `(`, or `,` makes the cursor resolve to the enclosing
+// container node instead of the token; the previous token decides whether the
+// cursor still sits in "new entry" position.
+function lastChildBefore(node: SyntaxNode, pos: number) {
+ let previous: SyntaxNode | null = null;
+ for (
+ let child = node.firstChild;
+ child && child.from < pos;
+ child = child.nextSibling
+ ) {
+ previous = child;
+ }
+ return previous;
+}
+
+function makePathCompletionHandler(
+ pathCompletions: ReadonlyMap<string, readonly Completion[]>,
+ validFor: RegExp,
+): CompletionHandler {
+ return (context, inner) => {
+ const resolved = getSyntaxCompletionPath(context, inner);
+ if (!resolved) return null;
+
+ const options = pathCompletions.get(resolved.path.join("."));
+ if (!options) return null;
+
+ return { from: context.pos - resolved.name.length, options, validFor };
+ };
+}
+
+function getPythonConstructorParameterCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let argumentList: SyntaxNode | null = null;
+ let name = "";
+
+ if (inner.name === "VariableName" && inner.parent?.name === "ArgList") {
+ const previous = inner.prevSibling;
+ if (previous?.name !== "(" && previous?.name !== ",") return null;
+ argumentList = inner.parent;
+ name = sliceNameToCursor(context, inner);
+ } else if (
+ (inner.name === "(" || inner.name === ",") &&
+ inner.parent?.name === "ArgList"
+ ) {
+ argumentList = inner.parent;
+ } else if (inner.name === "ArgList") {
+ const previous = lastChildBefore(inner, context.pos);
+ if (previous?.name === "(" || previous?.name === ",") {
+ argumentList = inner;
+ }
+ }
+
+ const call = argumentList?.parent;
+ const callee = call?.name === "CallExpression" ? call.firstChild : null;
+ if (callee?.name !== "VariableName") return null;
+
+ const constructorName = sliceNode(context, callee);
+ const parameters = PYTHON_CONSTRUCTOR_PARAMETERS.get(constructorName);
+ if (!parameters) return null;
+
+ const usedParameters = new Set<string>();
+ for (let child = argumentList?.firstChild; child; child = child.nextSibling) {
+ if (
+ child.name === "VariableName" &&
+ child.nextSibling?.name === "AssignOp"
+ ) {
+ // The keyword being edited stays available for its own completion.
+ if (child.from === inner.from && child.to === inner.to) continue;
+ usedParameters.add(sliceNode(context, child));
+ }
+ }
+
+ return {
+ from: context.pos - name.length,
+ options: parameters
+ .filter((parameter) => !usedParameters.has(parameter.label))
+ .map((parameter) => ({
+ ...parameter,
+ type: "property",
+ apply: `${parameter.label}=`,
+ })),
+ validFor: PYTHON_PROPERTY_NAME,
+ };
+}
+
+function getPythonResultConstructorCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ if (inner.name !== "VariableName" || inner.from >= context.pos) return null;
+
+ return {
+ from: inner.from,
+ options: PYTHON_RESULT_CONSTRUCTORS,
+ validFor: PYTHON_PROPERTY_NAME,
+ };
+}
+
+// Mirrors the validator's hasEvaluateFunction: an evaluator may be a
+// `function evaluate` declaration or a `const evaluate = …` arrow/function
+// expression, where the authoritative name is the declarator's.
+function getFunctionName(node: SyntaxNode, context: CompletionContext) {
+ if (node.name === "FunctionDeclaration") {
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (child.name === "VariableDefinition") {
+ return sliceNode(context, child);
+ }
+ }
+ return null;
+ }
+
+ if (node.name !== "ArrowFunction" && node.name !== "FunctionExpression") {
+ return null;
+ }
+ if (node.parent?.name !== "VariableDeclaration") return null;
+ for (
+ let sibling = node.prevSibling;
+ sibling && sibling.name !== ",";
+ sibling = sibling.prevSibling
+ ) {
+ if (sibling.name === "VariableDefinition") {
+ return sliceNode(context, sibling);
+ }
+ }
+ return null;
+}
+
+function getTypeScriptReturnTypeCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let annotation: SyntaxNode | null = null;
+ if (inner.name === "TypeName") {
+ for (let node = inner.parent; node; node = node.parent) {
+ if (node.name === "TypeAnnotation") {
+ annotation = node;
+ break;
+ }
+ if (SCOPE_NODES.has(node.name) || node.name === "ParamList") break;
+ }
+ } else if (inner.name === ":" && inner.parent?.name === "TypeAnnotation") {
+ annotation = inner.parent;
+ }
+ const fn = annotation?.parent;
+ if (!fn || getFunctionName(fn, context) !== "evaluate") return null;
+
+ const name =
+ inner.name === "TypeName" ? sliceNameToCursor(context, inner) : "";
+ return {
+ from: context.pos - name.length,
+ options: [TYPESCRIPT_EVALUATION_RESULT],
+ validFor: TYPESCRIPT_PROPERTY_NAME,
+ };
+}
+
+function getCurrentObjectProperty(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let object: SyntaxNode | null = null;
+ let property: SyntaxNode | null = null;
+ let name = "";
+
+ if (
+ inner.name === "PropertyDefinition" &&
+ inner.parent?.name === "Property" &&
+ OBJECT_NODES.has(inner.parent.parent?.name ?? "")
+ ) {
+ property = inner.parent;
+ object = property.parent;
+ name = sliceNameToCursor(context, inner);
+ } else if (
+ inner.name === "PropertyName" &&
+ inner.parent?.name === "PatternProperty" &&
+ OBJECT_NODES.has(inner.parent.parent?.name ?? "")
+ ) {
+ property = inner.parent;
+ object = property.parent;
+ name = sliceNameToCursor(context, inner);
+ } else if (
+ (inner.name === "{" || inner.name === ",") &&
+ OBJECT_NODES.has(inner.parent?.name ?? "")
+ ) {
+ object = inner.parent;
+ } else if (OBJECT_NODES.has(inner.name)) {
+ const previous = lastChildBefore(inner, context.pos);
+ if (previous?.name === "{" || previous?.name === ",") {
+ object = inner;
+ }
+ }
+
+ return object ? { object, property, name } : null;
+}
+
+function unwrapExpressionParent(node: SyntaxNode | null) {
+ while (node && EXPRESSION_WRAPPER_NODES.has(node.name)) {
+ node = node.parent;
+ }
+ return node;
+}
+
+function isEvaluateReturnObject(
+ object: SyntaxNode,
+ context: CompletionContext,
+) {
+ const container = unwrapExpressionParent(object.parent);
+ // Expression-body arrows return without a ReturnStatement:
+ // `const evaluate = (ctx) => ({ scores: [] })`.
+ if (container && SCOPE_NODES.has(container.name)) {
+ return getFunctionName(container, context) === "evaluate";
+ }
+ if (container?.name !== "ReturnStatement") return false;
+
+ for (let node = container.parent; node; node = node.parent) {
+ if (SCOPE_NODES.has(node.name)) {
+ return getFunctionName(node, context) === "evaluate";
+ }
+ }
+ return false;
+}
+
+function getPropertyName(node: SyntaxNode, context: CompletionContext) {
+ const name = node.firstChild;
+ if (name?.name !== "PropertyDefinition" && name?.name !== "PropertyName") {
+ return null;
+ }
+ return sliceNode(context, name);
+}
+
+function isTypeScriptScoreObject(
+ object: SyntaxNode,
+ context: CompletionContext,
+) {
+ const array = unwrapExpressionParent(object.parent);
+ const scoreProperty = ARRAY_NODES.has(array?.name ?? "")
+ ? unwrapExpressionParent(array?.parent ?? null)
+ : null;
+ const resultObject = scoreProperty?.parent;
+ return Boolean(
+ scoreProperty?.name === "Property" &&
+ getPropertyName(scoreProperty, context) === "scores" &&
+ resultObject &&
+ OBJECT_NODES.has(resultObject.name) &&
+ isEvaluateReturnObject(resultObject, context),
+ );
+}
+
+function getTypeScriptObjectPropertyCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ const current = getCurrentObjectProperty(context, inner);
+ if (!current) return null;
+
+ let properties: readonly { label: string; detail: string }[] | null = null;
+ if (isEvaluateReturnObject(current.object, context)) {
+ properties = TYPESCRIPT_CONTRACT.resultProperties;
+ } else if (isTypeScriptScoreObject(current.object, context)) {
+ properties = TYPESCRIPT_CONTRACT.scoreProperties;
+ }
+ if (!properties) return null;
+
+ const usedProperties = new Set<string>();
+ for (
+ let property = current.object.firstChild;
+ property;
+ property = property.nextSibling
+ ) {
+ if (
+ current.property &&
+ property.from === current.property.from &&
+ property.to === current.property.to
+ ) {
+ continue;
+ }
+ const name = getPropertyName(property, context);
+ if (name) usedProperties.add(name);
+ }
+
+ const options = properties
+ .filter((property) => !usedProperties.has(property.label))
+ .map((property) => ({
+ ...property,
+ type: "property",
+ apply: `${property.label}: `,
+ }));
+ return options.length > 0
+ ? {
+ from: context.pos - current.name.length,
+ options,
+ validFor: TYPESCRIPT_PROPERTY_NAME,
+ }
+ : null;
+}
+
+function getQuotedEnumValueCompletion(
+ context: CompletionContext,
+ value: SyntaxNode | null,
+ values: readonly string[],
+ detail: string,
+) {
+ const partial =
+ value && value.from <= context.pos
+ ? context.state.doc.sliceString(value.from, context.pos)
+ : "";
+ const quote = partial.startsWith("'") ? "'" : '"';
+ const from = partial ? (value?.from ?? context.pos) : context.pos;
+ const hasClosingQuote =
+ value?.name === "String" &&
+ value.to > context.pos &&
+ context.state.doc.sliceString(value.to - 1, value.to) === quote;
+
+ return {
+ from,
+ // Replace through the closing quote's content so accepting mid-value
+ // does not leave the old suffix behind ("CA|TEGORY" → "NUMERIC").
+ to: hasClosingQuote && value ? value.to - 1 : context.pos,
+ options: values.map((value) => ({
+ label: `${quote}${value}${quote}`,
+ // Keep an auto-inserted closing quote outside the filtered range and
+ // reuse it on acceptance, so both empty and partial strings complete.
+ ...(hasClosingQuote ? { apply: `${quote}${value}` } : {}),
+ type: "enum",
+ detail,
+ })),
+ };
+}
+
+function getTypeScriptDataTypeValueCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let property: SyntaxNode | null = inner;
+ while (
+ property &&
+ property.name !== "Property" &&
+ property.name !== "PatternProperty" &&
+ !OBJECT_NODES.has(property.name)
+ ) {
+ property = property.parent;
+ }
+ if (
+ (property?.name !== "Property" && property?.name !== "PatternProperty") ||
+ getPropertyName(property, context) !== "dataType" ||
+ !property.parent ||
+ !isTypeScriptScoreObject(property.parent, context)
+ ) {
+ return null;
+ }
+
+ for (
+ let node: SyntaxNode | null = inner;
+ node !== property;
+ node = node.parent
+ ) {
+ if (!node || DATA_TYPE_IGNORED_SYNTAX_NODES.has(node.name)) return null;
+ }
+
+ let colon = property.firstChild;
+ while (colon && colon.name !== ":") colon = colon.nextSibling;
+ if (!colon || context.pos < colon.to) return null;
+
+ return getQuotedEnumValueCompletion(
+ context,
+ colon.nextSibling,
+ TYPESCRIPT_CONTRACT.dataTypeValues,
+ "Score.dataType",
+ );
+}
+
+function getPythonDataTypeValueCompletion(
+ context: CompletionContext,
+ inner: SyntaxNode,
+) {
+ let argument = inner;
+ while (argument.parent?.name !== "ArgList") {
+ if (DATA_TYPE_IGNORED_SYNTAX_NODES.has(argument.name)) return null;
+ if (!argument.parent) return null;
+ argument = argument.parent;
+ }
+ if (DATA_TYPE_IGNORED_SYNTAX_NODES.has(argument.name)) return null;
+
+ const argumentList = argument.parent;
+ if (!argumentList) return null;
+ const call = argumentList.parent;
+ const callee = call?.name === "CallExpression" ? call.firstChild : null;
+ if (
+ callee?.name !== "VariableName" ||
+ sliceNode(context, callee) !== "Score"
+ ) {
+ return null;
+ }
+
+ const operator =
+ argument.name === "AssignOp"
+ ? argument
+ : argument.prevSibling?.name === "AssignOp"
+ ? argument.prevSibling
+ : null;
+ const parameter = operator?.prevSibling;
+ if (
+ parameter?.name !== "VariableName" ||
+ sliceNode(context, parameter) !== "data_type"
+ ) {
+ return null;
+ }
+
+ return getQuotedEnumValueCompletion(
+ context,
+ argument === operator ? null : argument,
+ PYTHON_CONTRACT.dataTypeValues,
+ "Score.data_type",
+ );
+}
+
+const COMPLETION_CONFIGS: Record<
+ CodeEvalSourceCodeLanguage,
+ {
+ language: typeof javascriptLanguage;
+ // Ordered syntax handlers; the first one returning a result wins.
+ handlers: readonly CompletionHandler[];
+ // Runs before the string/comment guard: enum values complete in strings.
+ dataTypeHandler: CompletionHandler;
+ }
+> = {
+ TYPESCRIPT: {
+ language: javascriptLanguage,
+ handlers: [
+ makePathCompletionHandler(
+ buildPathCompletions(
+ TYPESCRIPT_CONTRACT.pathProperties,
+ TYPESCRIPT_CONTRACT.toolCallProperties,
+ "ctx.observation.toolCalls",
+ ),
+ TYPESCRIPT_PROPERTY_NAME,
+ ),
+ getTypeScriptReturnTypeCompletion,
+ getTypeScriptObjectPropertyCompletion,
+ ],
+ dataTypeHandler: getTypeScriptDataTypeValueCompletion,
+ },
+ PYTHON: {
+ language: pythonLanguage,
+ handlers: [
+ makePathCompletionHandler(
+ buildPathCompletions(
+ PYTHON_CONTRACT.pathProperties,
+ PYTHON_CONTRACT.toolCallProperties,
+ "ctx.observation.tool_calls",
+ ),
+ PYTHON_PROPERTY_NAME,
+ ),
+ getPythonConstructorParameterCompletion,
+ getPythonResultConstructorCompletion,
+ ],
+ dataTypeHandler: getPythonDataTypeValueCompletion,
+ },
+};
+
+export function getCodeEvalCompletionSource(
+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,
+): CompletionSource {
+ const config = COMPLETION_CONFIGS[sourceCodeLanguage];
+
+ return (context: CompletionContext) => {
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
+
+ const dataTypeValue = config.dataTypeHandler(context, inner);
+ if (dataTypeValue) return dataTypeValue;
+
+ if (isInsideStringOrComment(inner)) return null;
+
+ for (const handler of config.handlers) {
+ const result = handler(context, inner);
+ if (result) return result;
+ }
+ return null;
+ };
+}
+
+export function getCodeEvalCompletionExtension(
+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,
+) {
+ return [
+ COMPLETION_CONFIGS[sourceCodeLanguage].language.data.of({
+ autocomplete: getCodeEvalCompletionSource(sourceCodeLanguage),
+ }),
+ autocompletion({
+ activateOnCompletion: (completion) =>
+ ENUM_VALUE_PROPERTIES.has(completion.label),
+ }),
+ ];
+}
diff --git a/web/src/features/evals/utils/code-eval-template-hover-docs.ts b/web/src/features/evals/utils/code-eval-template-hover-docs.ts
index 321e19b88c..a70b810122 100644
--- a/web/src/features/evals/utils/code-eval-template-hover-docs.ts
+++ b/web/src/features/evals/utils/code-eval-template-hover-docs.ts
@@ -1,7 +1,22 @@
-import type { CodeEvalSourceCodeLanguage } from "@/src/features/evals/utils/code-eval-template-starter-examples";
+import {
+ CODE_EVAL_COMPLETION_CONTRACT,
+ type CodeEvalSourceCodeLanguage,
+ type PythonCodeEvalCompletionName,
+ type TypeScriptCodeEvalCompletionName,
+} from "@/src/features/evals/utils/code-eval-template-starter-examples";
export type CodeEvalHoverDocs = Record<string, string>;
+// ToolCall-only hover keys collide with everyday identifiers (`type Foo`, a
+// local `index` or `id`), so the hover extension only documents them on
+// actual property accesses. `name` stays word-keyed: it doubles as the Score
+// property / keyword argument. Labels are identical across both languages.
+export const PROPERTY_ACCESS_ONLY_HOVER_KEYS: ReadonlySet<string> = new Set(
+ CODE_EVAL_COMPLETION_CONTRACT.TYPESCRIPT.toolCallProperties
+ .map((property) => property.label)
+ .filter((label) => label !== "name"),
+);
+
const TYPESCRIPT_SCORE_DOC = `type Score =
| (ScoreBase & { dataType: "NUMERIC"; value: number })
| (ScoreBase & { dataType: "BOOLEAN"; value: boolean })
@@ -85,6 +100,18 @@ The observation selected by the evaluator target.`,
toolCalls: `property observation.toolCalls: ToolCall[]
The tool calls recorded on the observation, in the order the model emitted them.`,
+ id: `property ToolCall.id: string
+
+The tool call identifier emitted by the model provider.`,
+ arguments: `property ToolCall.arguments: unknown
+
+The parsed tool arguments when the recorded value was valid JSON.`,
+ type: `property ToolCall.type: string
+
+The recorded tool-call type.`,
+ index: `property ToolCall.index: number
+
+The tool call position in the model response.`,
experiment: `property EvaluationContext.experiment?: {
itemExpectedOutput: any;
itemMetadata: any;
@@ -122,16 +149,17 @@ The Langfuse score data type.`,
value: `property Score.value: number | string | boolean
The score value. The allowed value depends on dataType: NUMERIC uses number, BOOLEAN uses boolean, and CATEGORICAL or TEXT use string.`,
- name: `property Score.name: string
+ name: `property Score.name or ToolCall.name: string
-The score name.`,
+The score name, or the function name invoked by a tool call.`,
comment: `property Score.comment?: string
The reasoning or explanation stored with the score.`,
configId: `property Score.configId?: string | null
The score config id to attach to the score.`,
-} satisfies CodeEvalHoverDocs;
+} satisfies CodeEvalHoverDocs &
+ Record<TypeScriptCodeEvalCompletionName, string>;
export const PYTHON_CODE_EVAL_HOVER_DOCS = {
evaluate: `def evaluate(ctx: EvaluationContext) -> EvaluationResult
@@ -160,6 +188,18 @@ The observation selected by the evaluator target.`,
The tool calls recorded on the observation, in the order the model emitted
them. arguments is the parsed argument object when the recorded value was
valid JSON.`,
+ id: `property ToolCall.id: str
+
+The tool call identifier emitted by the model provider.`,
+ arguments: `property ToolCall.arguments: Any
+
+The parsed tool arguments when the recorded value was valid JSON.`,
+ type: `property ToolCall.type: str
+
+The recorded tool-call type.`,
+ index: `property ToolCall.index: int
+
+The tool call position in the model response.`,
ExperimentContext: `@dataclass
class ExperimentContext:
item_expected_output: Any = None
@@ -208,16 +248,16 @@ The Langfuse score data type. Use NUMERIC, BOOLEAN, CATEGORICAL, or TEXT.`,
value: `property score.value: int | float | str | bool
The score value. The allowed value depends on data_type: NUMERIC uses a number, BOOLEAN uses a boolean, and CATEGORICAL or TEXT use a string.`,
- name: `property score.name: str
+ name: `property score.name or ToolCall.name: str
-The score name.`,
+The score name, or the function name invoked by a tool call.`,
comment: `property score.comment: str | None
The reasoning or explanation stored with the score.`,
config_id: `property score.config_id: str | None
The score config id to attach to the score.`,
-} satisfies CodeEvalHoverDocs;
+} satisfies CodeEvalHoverDocs & Record<PythonCodeEvalCompletionName, string>;
export function getCodeEvalHoverDocs(
sourceCodeLanguage: CodeEvalSourceCodeLanguage,
diff --git a/web/src/features/evals/utils/code-eval-template-starter-examples.ts b/web/src/features/evals/utils/code-eval-template-starter-examples.ts
index 40215c4686..1712682815 100644
--- a/web/src/features/evals/utils/code-eval-template-starter-examples.ts
+++ b/web/src/features/evals/utils/code-eval-template-starter-examples.ts
@@ -1,3 +1,155 @@
+import type { ToolCallForEval } from "@langfuse/shared";
+
+// Compact contract metadata drives editor completions and type-checks hover-doc
+// coverage. Keep the executable declarations below readable for users.
+const SCORE_DATA_TYPE_VALUES = [
+ "NUMERIC",
+ "BOOLEAN",
+ "CATEGORICAL",
+ "TEXT",
+] as const;
+
+export const CODE_EVAL_COMPLETION_CONTRACT = {
+ TYPESCRIPT: {
+ pathProperties: {
+ ctx: [
+ { label: "observation", detail: 'EvaluationContext["observation"]' },
+ {
+ label: "experiment",
+ detail: 'EvaluationContext["experiment"]',
+ },
+ ],
+ "ctx.observation": [
+ { label: "input", detail: "any" },
+ { label: "output", detail: "any" },
+ { label: "metadata", detail: "any" },
+ { label: "toolCalls", detail: "ToolCall[]" },
+ ],
+ "ctx.experiment": [
+ { label: "itemExpectedOutput", detail: "any" },
+ { label: "itemMetadata", detail: "any" },
+ ],
+ },
+ toolCallProperties: [
+ { label: "id", detail: "string" },
+ { label: "name", detail: "string" },
+ { label: "arguments", detail: "unknown" },
+ { label: "type", detail: "string" },
+ { label: "index", detail: "number" },
+ ],
+ resultType: { label: "EvaluationResult", detail: "{ scores: Score[] }" },
+ resultProperties: [{ label: "scores", detail: "Score[]" }],
+ scoreProperties: [
+ { label: "name", detail: "string" },
+ { label: "value", detail: "number | string | boolean" },
+ {
+ label: "dataType",
+ detail: '"NUMERIC" | "BOOLEAN" | "CATEGORICAL" | "TEXT"',
+ },
+ { label: "comment", detail: "string | undefined" },
+ { label: "configId", detail: "string | null | undefined" },
+ {
+ label: "metadata",
+ detail: "Record<string, unknown> | undefined",
+ },
+ ],
+ dataTypeValues: SCORE_DATA_TYPE_VALUES,
+ },
+ PYTHON: {
+ pathProperties: {
+ ctx: [
+ { label: "observation", detail: "ObservationContext" },
+ { label: "experiment", detail: "ExperimentContext | None" },
+ ],
+ "ctx.observation": [
+ { label: "input", detail: "Any" },
+ { label: "output", detail: "Any" },
+ { label: "metadata", detail: "Any" },
+ { label: "tool_calls", detail: "list[ToolCall]" },
+ ],
+ "ctx.experiment": [
+ { label: "item_expected_output", detail: "Any" },
+ { label: "item_metadata", detail: "Any" },
+ ],
+ },
+ toolCallProperties: [
+ { label: "id", detail: "str" },
+ { label: "name", detail: "str" },
+ { label: "arguments", detail: "Any" },
+ { label: "type", detail: "str" },
+ { label: "index", detail: "int" },
+ ],
+ resultConstructors: [
+ { label: "EvaluationResult", detail: "dataclass" },
+ { label: "Score", detail: "dataclass" },
+ ],
+ constructorParameters: {
+ EvaluationResult: [{ label: "scores", detail: "list[Score]" }],
+ Score: [
+ { label: "value", detail: "int | float | str | bool" },
+ { label: "name", detail: "str" },
+ { label: "data_type", detail: "str | None" },
+ { label: "comment", detail: "str | None" },
+ { label: "config_id", detail: "str | None" },
+ { label: "metadata", detail: "dict[str, Any] | None" },
+ ],
+ },
+ dataTypeValues: SCORE_DATA_TYPE_VALUES,
+ },
+} as const;
+
+type Labels<T> = T extends readonly { label: infer Label extends string }[]
+ ? Label
+ : never;
+
+type TypeScriptCompletionContract =
+ (typeof CODE_EVAL_COMPLETION_CONTRACT)["TYPESCRIPT"];
+type TypeScriptPathProperties =
+ TypeScriptCompletionContract["pathProperties"][keyof TypeScriptCompletionContract["pathProperties"]];
+
+export type TypeScriptCodeEvalCompletionName =
+ | Labels<TypeScriptPathProperties>
+ | Labels<TypeScriptCompletionContract["toolCallProperties"]>
+ | TypeScriptCompletionContract["resultType"]["label"]
+ | Labels<TypeScriptCompletionContract["resultProperties"]>
+ | Labels<TypeScriptCompletionContract["scoreProperties"]>;
+
+type PythonCompletionContract =
+ (typeof CODE_EVAL_COMPLETION_CONTRACT)["PYTHON"];
+type PythonPathProperties =
+ PythonCompletionContract["pathProperties"][keyof PythonCompletionContract["pathProperties"]];
+type PythonConstructorParameters =
+ PythonCompletionContract["constructorParameters"][keyof PythonCompletionContract["constructorParameters"]];
+
+export type PythonCodeEvalCompletionName =
+ | Labels<PythonPathProperties>
+ | Labels<PythonCompletionContract["toolCallProperties"]>
+ | Labels<PythonCompletionContract["resultConstructors"]>
+ | Labels<PythonConstructorParameters>;
+
+type MutuallyExtends<A, B> = [A] extends [B]
+ ? [B] extends [A]
+ ? true
+ : false
+ : false;
+type Expect<T extends true> = T;
+
+// Compile-time lockstep with the runtime evaluator payload: adding or
+// removing a field on ToolCallForEval breaks the web build until the editor
+// completions (and, via the hover-doc Record checks, the hover docs) follow.
+export type TypeScriptToolCallCompletionsMatchRuntime = Expect<
+ MutuallyExtends<
+ Labels<TypeScriptCompletionContract["toolCallProperties"]>,
+ keyof ToolCallForEval
+ >
+>;
+export type PythonToolCallCompletionsMatchRuntime = Expect<
+ MutuallyExtends<
+ Labels<PythonCompletionContract["toolCallProperties"]>,
+ keyof ToolCallForEval
+ >
+>;
+
export const TYPESCRIPT_CODE_EVAL_CONTRACT = `type ToolCall = {
id: string;
name: string;