@novedu/cli 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -8
- package/dist/main.js +1693 -591
- package/package.json +3 -3
package/dist/main.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
2
|
import { Command } from "commander";
|
|
4
3
|
import { readFile, writeFile } from "node:fs/promises";
|
|
5
4
|
import { basename, dirname, join, resolve } from "node:path";
|
|
6
5
|
import { spawn } from "node:child_process";
|
|
6
|
+
import { globSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { createServer } from "node:http";
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
9
|
import { CryptoProvider, PublicClientApplication } from "@azure/msal-node";
|
|
@@ -226,18 +226,19 @@ function failJson(value) {
|
|
|
226
226
|
* not abort the run).
|
|
227
227
|
*/
|
|
228
228
|
async function performApiRequest(options) {
|
|
229
|
-
const fail = (value) => {
|
|
229
|
+
const fail = (value, extra = {}) => {
|
|
230
230
|
if (!options.quiet) failJson(value);
|
|
231
231
|
return {
|
|
232
232
|
ok: false,
|
|
233
|
-
error: value
|
|
233
|
+
error: value,
|
|
234
|
+
...extra
|
|
234
235
|
};
|
|
235
236
|
};
|
|
236
237
|
let token;
|
|
237
238
|
try {
|
|
238
239
|
token = await getAccessToken();
|
|
239
240
|
} catch (error) {
|
|
240
|
-
if (error instanceof NotSignedInError) return fail({ message: error.message });
|
|
241
|
+
if (error instanceof NotSignedInError) return fail({ message: error.message }, { authFailed: true });
|
|
241
242
|
throw error;
|
|
242
243
|
}
|
|
243
244
|
const server = resolveServerUrl(options.server);
|
|
@@ -260,7 +261,10 @@ async function performApiRequest(options) {
|
|
|
260
261
|
} catch {
|
|
261
262
|
payload = void 0;
|
|
262
263
|
}
|
|
263
|
-
if (!response.ok) return fail(payload ?? { message: `${server} rejected the request: HTTP ${response.status}` }
|
|
264
|
+
if (!response.ok) return fail(payload ?? { message: `${server} rejected the request: HTTP ${response.status}` }, {
|
|
265
|
+
status: response.status,
|
|
266
|
+
...response.status === 401 || response.status === 403 ? { authFailed: true } : {}
|
|
267
|
+
});
|
|
264
268
|
return {
|
|
265
269
|
ok: true,
|
|
266
270
|
payload
|
|
@@ -876,173 +880,55 @@ function registerCodes(program) {
|
|
|
876
880
|
});
|
|
877
881
|
}
|
|
878
882
|
//#endregion
|
|
879
|
-
//#region
|
|
880
|
-
const
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
let content;
|
|
890
|
-
try {
|
|
891
|
-
content = options.file === void 0 ? await readStdin() : await readFile(options.file, "utf8");
|
|
892
|
-
} catch (error) {
|
|
893
|
-
failJson({ message: `Could not read ${options.file}: ${error instanceof Error ? error.message : error}` });
|
|
894
|
-
return;
|
|
895
|
-
}
|
|
896
|
-
await runApiRequest({
|
|
897
|
-
server: options.server,
|
|
898
|
-
path: `/api/files/${encodeURIComponent(name)}`,
|
|
899
|
-
method: "PUT",
|
|
900
|
-
body: {
|
|
901
|
-
...options.kind === void 0 ? {} : { kind: options.kind },
|
|
902
|
-
content
|
|
903
|
-
}
|
|
904
|
-
});
|
|
905
|
-
});
|
|
906
|
-
files.command("list").description("List app-hosted YAML files (defaults to only your own, like the web list)").option("--search <q>", "contains-filter over name/title/description").option("--all", "include files last written by other teachers").option(...SERVER_OPTION$2).action(async (options) => {
|
|
907
|
-
const params = new URLSearchParams();
|
|
908
|
-
if (options.search) params.set("q", options.search);
|
|
909
|
-
if (options.all) params.set("mine", "0");
|
|
910
|
-
const query = params.toString();
|
|
911
|
-
await runApiRequest({
|
|
912
|
-
server: options.server,
|
|
913
|
-
path: `/api/files${query ? `?${query}` : ""}`
|
|
914
|
-
});
|
|
915
|
-
});
|
|
916
|
-
}
|
|
883
|
+
//#region ../lib/quiz-verdict-schema.ts
|
|
884
|
+
const QUIZ_VERDICT_SCHEMA = z.object({
|
|
885
|
+
result: z.enum([
|
|
886
|
+
"correct",
|
|
887
|
+
"partial",
|
|
888
|
+
"incorrect"
|
|
889
|
+
]),
|
|
890
|
+
feedback: z.string()
|
|
891
|
+
});
|
|
892
|
+
const QUIZ_VERDICT_ENUM = QUIZ_VERDICT_SCHEMA.shape.result;
|
|
917
893
|
//#endregion
|
|
918
|
-
//#region ../lib/
|
|
894
|
+
//#region ../lib/eval-schema.ts
|
|
895
|
+
/** The three verdicts in canonical order (best → worst); the sort key for expected sets. */
|
|
896
|
+
const EVAL_VERDICTS = QUIZ_VERDICT_ENUM.options;
|
|
919
897
|
/**
|
|
920
|
-
*
|
|
921
|
-
*
|
|
922
|
-
* both map to `image/jpeg`, `svg` to `image/svg+xml`.
|
|
898
|
+
* Eval ids share the flat namespace of report headers and `--out` files, so they stay
|
|
899
|
+
* URL- and YAML-plain: an alphanumeric start, then alphanumerics, `.`, `-` or `_`.
|
|
923
900
|
*/
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
bytes = await readFile(options.file);
|
|
952
|
-
} catch (error) {
|
|
953
|
-
failJson({ message: `Could not read ${options.file}: ${error instanceof Error ? error.message : error}` });
|
|
954
|
-
return;
|
|
955
|
-
}
|
|
956
|
-
const slot = await performApiRequest({
|
|
957
|
-
server: options.server,
|
|
958
|
-
path: `/api/images/${encodeURIComponent(name)}`,
|
|
959
|
-
method: "POST",
|
|
960
|
-
body: {
|
|
961
|
-
mime,
|
|
962
|
-
byteSize: bytes.length
|
|
963
|
-
}
|
|
964
|
-
});
|
|
965
|
-
if (!slot.ok) return;
|
|
966
|
-
const { uploadUrl, blobPath } = slot.payload ?? {};
|
|
967
|
-
if (typeof uploadUrl !== "string" || typeof blobPath !== "string") {
|
|
968
|
-
failJson({ message: "Unexpected response from the server." });
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
let putResponse;
|
|
972
|
-
try {
|
|
973
|
-
putResponse = await fetch(uploadUrl, {
|
|
974
|
-
method: "PUT",
|
|
975
|
-
headers: {
|
|
976
|
-
"x-ms-blob-type": "BlockBlob",
|
|
977
|
-
"content-type": mime
|
|
978
|
-
},
|
|
979
|
-
body: new Uint8Array(bytes)
|
|
980
|
-
});
|
|
981
|
-
} catch (error) {
|
|
982
|
-
failJson({ message: `Could not reach storage: ${error instanceof Error ? error.message : error}` });
|
|
983
|
-
return;
|
|
984
|
-
}
|
|
985
|
-
if (!putResponse.ok) {
|
|
986
|
-
failJson({ message: `The upload to storage failed: HTTP ${putResponse.status}. Try again.` });
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
await runApiRequest({
|
|
990
|
-
server: options.server,
|
|
991
|
-
path: `/api/images/${encodeURIComponent(name)}/confirm`,
|
|
992
|
-
method: "POST",
|
|
993
|
-
body: {
|
|
994
|
-
blobPath,
|
|
995
|
-
mime,
|
|
996
|
-
...options.credit === void 0 ? {} : { credit: options.credit }
|
|
997
|
-
}
|
|
998
|
-
});
|
|
999
|
-
});
|
|
1000
|
-
images.command("list").description("List app-hosted images (defaults to only your own, like the web list)").option("--search <q>", "contains-filter over the name").option("--all", "include images uploaded by other teachers").option(...SERVER_OPTION$1).action(async (options) => {
|
|
1001
|
-
const params = new URLSearchParams();
|
|
1002
|
-
if (options.search) params.set("q", options.search);
|
|
1003
|
-
if (options.all) params.set("mine", "0");
|
|
1004
|
-
const query = params.toString();
|
|
1005
|
-
await runApiRequest({
|
|
1006
|
-
server: options.server,
|
|
1007
|
-
path: `/api/images${query ? `?${query}` : ""}`
|
|
1008
|
-
});
|
|
1009
|
-
});
|
|
1010
|
-
}
|
|
1011
|
-
//#endregion
|
|
1012
|
-
//#region src/commands/login.ts
|
|
1013
|
-
function registerLogin(program) {
|
|
1014
|
-
program.command("login").description("Sign in to Microsoft Entra ID (opens your browser)").option("--device-code", "sign in with the device code flow instead (for machines without a browser; the tenant must allow it)").addHelpText("after", `
|
|
1015
|
-
Sign-in is the one human-assisted step: by default a browser window opens for
|
|
1016
|
-
the Microsoft sign-in (first-time users see a one-time consent prompt). On a
|
|
1017
|
-
machine without a browser, --device-code prints a verification URL and a code
|
|
1018
|
-
to enter from any other device — note that some tenants block the device code
|
|
1019
|
-
flow by policy (error 53003). Every other command then works non-interactively
|
|
1020
|
-
from the cached credentials. Already signed in? The command says so and exits
|
|
1021
|
-
— it never blocks.`).action(async (options) => {
|
|
1022
|
-
const pca = buildPca();
|
|
1023
|
-
const cached = await acquireSilent(pca);
|
|
1024
|
-
if (cached) {
|
|
1025
|
-
console.log(`Already signed in as ${displayName(cached)}.`);
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
|
-
const result = options.deviceCode ? await acquireByDeviceCode(pca, (message) => console.log(message)) : await acquireInteractive(pca, (url) => {
|
|
1029
|
-
console.log("A browser window should open for the Microsoft sign-in.");
|
|
1030
|
-
console.log(`If it does not, open this URL yourself:\n${url}`);
|
|
1031
|
-
});
|
|
1032
|
-
console.log(`Signed in as ${displayName(result)}.`);
|
|
1033
|
-
});
|
|
901
|
+
const EVAL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
902
|
+
const MAX_ID_LENGTH = 128;
|
|
903
|
+
const expectSchema = z.union([QUIZ_VERDICT_ENUM, z.array(QUIZ_VERDICT_ENUM).min(1)]).meta({ description: "The verdict this answer must be graded with: one of \"correct\", \"partial\", \"incorrect\", or a non-empty list of acceptable verdicts (e.g. [correct, partial]) when more than one grading is defensible." });
|
|
904
|
+
/** One golden answer: the student text plus the verdict(s) the grader must produce. */
|
|
905
|
+
const EvalAnswerSchema = z.strictObject({
|
|
906
|
+
expect: expectSchema,
|
|
907
|
+
answer: z.string().min(1).meta({ description: "The student answer to grade, verbatim. Written as a YAML block scalar (|) for multi-line answers." })
|
|
908
|
+
});
|
|
909
|
+
/** All golden answers for ONE question of the target quiz. */
|
|
910
|
+
const EvalQuestionSchema = z.strictObject({
|
|
911
|
+
question: z.string().min(1).meta({ description: "The question id in the target quiz. For a question imported through quiz_files this is the namespaced \"<alias>/<id>\" form." }),
|
|
912
|
+
answers: z.array(EvalAnswerSchema).min(1).meta({ description: "The golden answers for this question — at least one." })
|
|
913
|
+
});
|
|
914
|
+
/** The whole eval file. */
|
|
915
|
+
const EvalYamlSchema = z.strictObject({
|
|
916
|
+
id: z.string().regex(EVAL_ID_PATTERN).max(MAX_ID_LENGTH).meta({ description: "Stable identifier of this eval, shown in the run report. Letters, digits, dot, dash and underscore." }),
|
|
917
|
+
target: z.string().min(1).meta({ description: "The quiz YAML this eval grades against — a path relative to THIS file, or an absolute http(s) URL." }),
|
|
918
|
+
questions: z.array(EvalQuestionSchema).min(1).meta({ description: "The evaluated questions — at least one, each with its golden answers." })
|
|
919
|
+
});
|
|
920
|
+
/**
|
|
921
|
+
* The canonical expected-verdict SET of one golden answer: a single verdict or a list,
|
|
922
|
+
* deduped and sorted into `EVAL_VERDICTS` order. Canonical because the confusion
|
|
923
|
+
* matrix keys its rows by this set — `correct|partial` must be one row no matter which
|
|
924
|
+
* order the author happened to write it in.
|
|
925
|
+
*/
|
|
926
|
+
function normalizeExpect(expect) {
|
|
927
|
+
return [...new Set(Array.isArray(expect) ? expect : [expect])].sort((a, b) => EVAL_VERDICTS.indexOf(a) - EVAL_VERDICTS.indexOf(b));
|
|
1034
928
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
program.command("logout").description("Sign out: remove the cached credentials from this machine").addHelpText("after", `
|
|
1039
|
-
Purely local — already-issued access tokens stay valid until they expire
|
|
1040
|
-
(about an hour). Running it while signed out is fine.`).action(async () => {
|
|
1041
|
-
const cache = buildPca().getTokenCache();
|
|
1042
|
-
for (const account of await cache.getAllAccounts()) await cache.removeAccount(account);
|
|
1043
|
-
rmSync(TOKEN_CACHE_PATH, { force: true });
|
|
1044
|
-
console.log("Signed out.");
|
|
1045
|
-
});
|
|
929
|
+
/** The confusion matrix's row key for an expected set (already canonical). */
|
|
930
|
+
function expectedKey(expected) {
|
|
931
|
+
return expected.join("|");
|
|
1046
932
|
}
|
|
1047
933
|
//#endregion
|
|
1048
934
|
//#region ../lib/coding-proxy.ts
|
|
@@ -2705,15 +2591,9 @@ async function loadQuizFrom(url, fetcher, opts = {}) {
|
|
|
2705
2591
|
};
|
|
2706
2592
|
}
|
|
2707
2593
|
}
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
result: z.enum([
|
|
2712
|
-
"correct",
|
|
2713
|
-
"partial",
|
|
2714
|
-
"incorrect"
|
|
2715
|
-
]),
|
|
2716
|
-
feedback: z.string()
|
|
2594
|
+
const tutorToolNameSchema = z.enum(["random_number"]).meta({
|
|
2595
|
+
id: "tutorToolName",
|
|
2596
|
+
description: "Name of a built-in tutor tool."
|
|
2717
2597
|
});
|
|
2718
2598
|
//#endregion
|
|
2719
2599
|
//#region ../lib/tutors/schemas.ts
|
|
@@ -2750,6 +2630,7 @@ const TutorSchema = z.strictObject({
|
|
|
2750
2630
|
id: "llm",
|
|
2751
2631
|
description: "The model and provider that back this tutor."
|
|
2752
2632
|
}),
|
|
2633
|
+
tools: z.array(tutorToolNameSchema).default([]).meta({ description: "Optional built-in tools the tutor's model may call (e.g. random_number). Off by default; mention enabled tools in tutor_instructions so the model uses them." }),
|
|
2753
2634
|
prompt: z.strictObject({
|
|
2754
2635
|
fragment_files: z.array(FragmentFileRefSchema).default([]).meta({ description: "Optional fragment libraries used by this tutor." }),
|
|
2755
2636
|
text_files: z.array(TextFileRefSchema).default([]).meta({ description: "Optional plain-text files (markdown / source) embedded verbatim via {{file \"alias\"}} markers." }),
|
|
@@ -2790,6 +2671,7 @@ async function loadAndBuildTutorPrompt(url, fetchImpl, opts = {}) {
|
|
|
2790
2671
|
model: tutor.llm.model,
|
|
2791
2672
|
provider: tutor.llm.provider,
|
|
2792
2673
|
imageInput: tutor.llm.imageInput ?? true,
|
|
2674
|
+
tools: tutor.tools,
|
|
2793
2675
|
anonymous: tutor.anonymous ?? true,
|
|
2794
2676
|
title: tutor.title,
|
|
2795
2677
|
description: tutor.description,
|
|
@@ -2961,7 +2843,8 @@ const promptDumpers = {
|
|
|
2961
2843
|
provider: result.provider,
|
|
2962
2844
|
model: result.model
|
|
2963
2845
|
},
|
|
2964
|
-
system: result.prompt
|
|
2846
|
+
system: result.prompt,
|
|
2847
|
+
tools: result.tools
|
|
2965
2848
|
}
|
|
2966
2849
|
};
|
|
2967
2850
|
} },
|
|
@@ -3074,267 +2957,12 @@ function promptSections(dump) {
|
|
|
3074
2957
|
}
|
|
3075
2958
|
}
|
|
3076
2959
|
//#endregion
|
|
3077
|
-
//#region
|
|
3078
|
-
const cliFetcher = async (url) => {
|
|
3079
|
-
if (url.startsWith("file:")) try {
|
|
3080
|
-
const text = await readFile(fileURLToPath(url), "utf8");
|
|
3081
|
-
return {
|
|
3082
|
-
ok: true,
|
|
3083
|
-
status: 200,
|
|
3084
|
-
text: async () => text
|
|
3085
|
-
};
|
|
3086
|
-
} catch {
|
|
3087
|
-
return {
|
|
3088
|
-
ok: false,
|
|
3089
|
-
status: 404,
|
|
3090
|
-
text: async () => ""
|
|
3091
|
-
};
|
|
3092
|
-
}
|
|
3093
|
-
return defaultFetcher(url);
|
|
3094
|
-
};
|
|
3095
|
-
//#endregion
|
|
3096
|
-
//#region src/format.ts
|
|
3097
|
-
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
3098
|
-
const paint = (code, s) => useColor ? `\x1b[${code}m${s}\x1b[0m` : s;
|
|
3099
|
-
const green = (s) => paint("32", s);
|
|
3100
|
-
const red = (s) => paint("31", s);
|
|
3101
|
-
const yellow = (s) => paint("33", s);
|
|
3102
|
-
const dim = (s) => paint("2", s);
|
|
3103
|
-
/** Append the context fields an error/warning carries, when present. */
|
|
3104
|
-
function context(item) {
|
|
3105
|
-
const parts = [];
|
|
3106
|
-
if (item.fileAlias) parts.push(`file=${item.fileAlias}`);
|
|
3107
|
-
if (item.fragmentId) parts.push(`fragment=${item.fragmentId}`);
|
|
3108
|
-
if ("questionId" in item && item.questionId) parts.push(`question=${item.questionId}`);
|
|
3109
|
-
if (item.variable) parts.push(`variable=${item.variable}`);
|
|
3110
|
-
if ("url" in item && item.url) parts.push(`url=${item.url}`);
|
|
3111
|
-
if ("expectedType" in item && item.expectedType) parts.push(`expected=${item.expectedType}`);
|
|
3112
|
-
if ("actualType" in item && item.actualType) parts.push(`actual=${item.actualType}`);
|
|
3113
|
-
return parts.length ? dim(` (${parts.join(", ")})`) : "";
|
|
3114
|
-
}
|
|
3115
|
-
function renderWarnings(warnings) {
|
|
3116
|
-
return warnings.map((w) => ` ${yellow("⚠")} ${yellow(w.code)} ${w.message}${context(w)}`);
|
|
3117
|
-
}
|
|
2960
|
+
//#region ../lib/quiz-schema.ts
|
|
3118
2961
|
/**
|
|
3119
|
-
*
|
|
3120
|
-
*
|
|
3121
|
-
*
|
|
3122
|
-
*
|
|
3123
|
-
*/
|
|
3124
|
-
function renderErrors(errors) {
|
|
3125
|
-
const lines = [];
|
|
3126
|
-
for (const e of errors) {
|
|
3127
|
-
lines.push(` ${red("✗")} ${red(e.code)} ${e.message}${context(e)}`);
|
|
3128
|
-
if (e.zodIssues) for (const issue of formatZodIssues(e.zodIssues)) lines.push(` ${dim(issue)}`);
|
|
3129
|
-
}
|
|
3130
|
-
return lines;
|
|
3131
|
-
}
|
|
3132
|
-
function formatResult(result, source) {
|
|
3133
|
-
const lines = [];
|
|
3134
|
-
if (result.ok) {
|
|
3135
|
-
lines.push(green(`✔ Valid tutor`) + dim(` — ${source}`));
|
|
3136
|
-
lines.push(` model: ${result.model}`);
|
|
3137
|
-
lines.push(` system prompt: ${result.prompt.length} chars`);
|
|
3138
|
-
lines.push(` imageInput: ${result.imageInput} anonymous: ${result.anonymous}` + (result.exampleQuestions.length ? ` exampleQuestions: ${result.exampleQuestions.length}` : ""));
|
|
3139
|
-
if (result.warnings.length) {
|
|
3140
|
-
lines.push("");
|
|
3141
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3142
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3143
|
-
}
|
|
3144
|
-
return lines.join("\n");
|
|
3145
|
-
}
|
|
3146
|
-
lines.push(red(`✘ Invalid tutor`) + dim(` — ${source}`));
|
|
3147
|
-
lines.push("");
|
|
3148
|
-
lines.push(red(`${result.errors.length} error(s):`));
|
|
3149
|
-
lines.push(...renderErrors(result.errors));
|
|
3150
|
-
if (result.warnings.length) {
|
|
3151
|
-
lines.push("");
|
|
3152
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3153
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3154
|
-
}
|
|
3155
|
-
return lines.join("\n");
|
|
3156
|
-
}
|
|
3157
|
-
/** Same renderer, for a standalone fragment-FILE check (`--kind fragment`). */
|
|
3158
|
-
function formatFragmentResult(result, source) {
|
|
3159
|
-
const lines = [];
|
|
3160
|
-
if (result.ok) {
|
|
3161
|
-
lines.push(green(`✔ Valid fragment file`) + dim(` — ${source}`));
|
|
3162
|
-
lines.push(` id: ${result.fragmentFileId}`);
|
|
3163
|
-
lines.push(` fragments: ${result.fragmentIds.length}` + (result.fragmentIds.length ? ` (${result.fragmentIds.join(", ")})` : ""));
|
|
3164
|
-
if (result.warnings.length) {
|
|
3165
|
-
lines.push("");
|
|
3166
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3167
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3168
|
-
}
|
|
3169
|
-
return lines.join("\n");
|
|
3170
|
-
}
|
|
3171
|
-
lines.push(red(`✘ Invalid fragment file`) + dim(` — ${source}`));
|
|
3172
|
-
lines.push("");
|
|
3173
|
-
lines.push(red(`${result.errors.length} error(s):`));
|
|
3174
|
-
lines.push(...renderErrors(result.errors));
|
|
3175
|
-
if (result.warnings.length) {
|
|
3176
|
-
lines.push("");
|
|
3177
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3178
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3179
|
-
}
|
|
3180
|
-
return lines.join("\n");
|
|
3181
|
-
}
|
|
3182
|
-
/**
|
|
3183
|
-
* Shared tail for the quiz/writing renderers: on failure, the error list (with any
|
|
3184
|
-
* flattened Zod issues); plus any warnings on either branch.
|
|
3185
|
-
*/
|
|
3186
|
-
function renderFailureAndWarnings(result, label, source) {
|
|
3187
|
-
const lines = [red(`✘ Invalid ${label}`) + dim(` — ${source}`), ""];
|
|
3188
|
-
lines.push(red(`${result.errors.length} error(s):`));
|
|
3189
|
-
lines.push(...renderErrors(result.errors));
|
|
3190
|
-
if (result.warnings.length) {
|
|
3191
|
-
lines.push("");
|
|
3192
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3193
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3194
|
-
}
|
|
3195
|
-
return lines.join("\n");
|
|
3196
|
-
}
|
|
3197
|
-
/** Renderer for a quiz check (`--kind quiz`). */
|
|
3198
|
-
function formatQuizResult(result, source) {
|
|
3199
|
-
if (!result.ok) return renderFailureAndWarnings(result, "quiz", source);
|
|
3200
|
-
const lines = [green(`✔ Valid quiz`) + dim(` — ${source}`)];
|
|
3201
|
-
lines.push(` id: ${result.quizId}`);
|
|
3202
|
-
lines.push(` model: ${result.model}`);
|
|
3203
|
-
lines.push(` questions: ${result.questionCount} anonymous: ${result.anonymous}`);
|
|
3204
|
-
if (result.warnings.length) {
|
|
3205
|
-
lines.push("");
|
|
3206
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3207
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3208
|
-
}
|
|
3209
|
-
return lines.join("\n");
|
|
3210
|
-
}
|
|
3211
|
-
/** Renderer for a writing-activity check (`--kind writing`). */
|
|
3212
|
-
function formatWritingResult(result, source) {
|
|
3213
|
-
if (!result.ok) return renderFailureAndWarnings(result, "writing activity", source);
|
|
3214
|
-
const lines = [green(`✔ Valid writing activity`) + dim(` — ${source}`)];
|
|
3215
|
-
lines.push(` id: ${result.writingId}`);
|
|
3216
|
-
lines.push(` model: ${result.model}`);
|
|
3217
|
-
lines.push(` anonymous: ${result.anonymous}`);
|
|
3218
|
-
if (result.warnings.length) {
|
|
3219
|
-
lines.push("");
|
|
3220
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3221
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3222
|
-
}
|
|
3223
|
-
return lines.join("\n");
|
|
3224
|
-
}
|
|
3225
|
-
/**
|
|
3226
|
-
* Renderer for a coding-activity check (`--kind coding`). Coding is ALWAYS anonymous
|
|
3227
|
-
* (the API path carries no per-student identity), so — unlike quiz/writing — that is
|
|
3228
|
-
* shown as a fixed note, not a per-file value.
|
|
3229
|
-
*/
|
|
3230
|
-
function formatCodingResult(result, source) {
|
|
3231
|
-
if (!result.ok) return renderFailureAndWarnings(result, "coding activity", source);
|
|
3232
|
-
const lines = [green(`✔ Valid coding activity`) + dim(` — ${source}`)];
|
|
3233
|
-
lines.push(` id: ${result.codingId}`);
|
|
3234
|
-
lines.push(` model: ${result.model}`);
|
|
3235
|
-
lines.push(` anonymous: true ${dim("(always — the API path carries no identity)")}`);
|
|
3236
|
-
if (result.warnings.length) {
|
|
3237
|
-
lines.push("");
|
|
3238
|
-
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3239
|
-
lines.push(...renderWarnings(result.warnings));
|
|
3240
|
-
}
|
|
3241
|
-
return lines.join("\n");
|
|
3242
|
-
}
|
|
3243
|
-
/**
|
|
3244
|
-
* Renderer for a prompt dump (`prompts`). Kind-agnostic by construction: the envelope
|
|
3245
|
-
* (kind / id / provider+model) plus one line per prompt with its character count — the
|
|
3246
|
-
* sections come from `promptSections`, so a new kind needs no change here. `--json`
|
|
3247
|
-
* carries the prompt text itself.
|
|
3248
|
-
*/
|
|
3249
|
-
function formatPromptDump(dump, sections, source) {
|
|
3250
|
-
const lines = [green(`✔ Prompts — ${dump.kind}`) + dim(` — ${source}`)];
|
|
3251
|
-
lines.push(` id: ${dump.id}`);
|
|
3252
|
-
lines.push(` provider: ${dump.llm.provider} model: ${dump.llm.model}`);
|
|
3253
|
-
lines.push(` prompts: ${sections.length}`);
|
|
3254
|
-
for (const section of sections) lines.push(` ${section.name}: ${section.text.length} chars`);
|
|
3255
|
-
lines.push("");
|
|
3256
|
-
lines.push(dim(" Run again with --json for the full prompt text."));
|
|
3257
|
-
return lines.join("\n");
|
|
3258
|
-
}
|
|
3259
|
-
//#endregion
|
|
3260
|
-
//#region ../lib/coding-schema.ts
|
|
3261
|
-
const CodingYamlSchema = z.strictObject({
|
|
3262
|
-
id: z.string().min(1).meta({ description: "Short machine-readable activity id, e.g. beginner-typescript." }),
|
|
3263
|
-
name: z.string().optional().meta({ description: "Optional human-readable label (not shown to the student)." }),
|
|
3264
|
-
title: z.string().optional().meta({ description: "Optional label shown to the student on the /<code> connection page." }),
|
|
3265
|
-
llm: z.strictObject({
|
|
3266
|
-
model: z.string().min(1).meta({ description: "The model that answers. SERVER-ONLY and PINNED: the proxy always uses this model and ignores whatever model the coding agent sends." }),
|
|
3267
|
-
provider: providerSchema
|
|
3268
|
-
}).meta({
|
|
3269
|
-
id: "llm",
|
|
3270
|
-
description: "The pinned model and provider that answer coding requests."
|
|
3271
|
-
}),
|
|
3272
|
-
fragment_files: z.array(FragmentFileRefSchema).default([]).meta({ description: "Optional fragment libraries this activity pulls shared prompt fragments from." }),
|
|
3273
|
-
text_files: z.array(TextFileRefSchema).default([]).meta({ description: "Optional plain-text files (markdown / source, e.g. a sample solution) embedded verbatim into instructions via {{file \"alias\"}} markers." }),
|
|
3274
|
-
instructions: z.string().min(1).meta({ description: "The assistant's system prompt. SERVER-ONLY: never sent to the browser or the coding agent, and appended AFTER the coding tool's own prompt (so the teacher has the final word). Constrain the assistant to what your class has learned. When any fragment_files or text_files are declared it is a Handlebars template: place fragments inline with {{fragment \"alias.id\" …}} and embed text files with {{file \"alias\"}} (optionally {{file \"alias\" from=10 to=40}} for a line range; escape a literal {{ as \\{{)." })
|
|
3275
|
-
});
|
|
3276
|
-
//#endregion
|
|
3277
|
-
//#region ../lib/coding-validate.ts
|
|
3278
|
-
/**
|
|
3279
|
-
* Extract metadata from an already-schema-validated coding value. Split from
|
|
3280
|
-
* `checkCodingValue` so `loadAndCheckCoding` can reuse the single `validate` it already
|
|
3281
|
-
* ran (no second parse of the same document against the same schema).
|
|
3282
|
-
*/
|
|
3283
|
-
function checkCodingParsed(coding) {
|
|
3284
|
-
return {
|
|
3285
|
-
ok: true,
|
|
3286
|
-
codingId: coding.id,
|
|
3287
|
-
model: coding.llm.model,
|
|
3288
|
-
provider: coding.llm.provider,
|
|
3289
|
-
title: coding.title ?? null,
|
|
3290
|
-
warnings: []
|
|
3291
|
-
};
|
|
3292
|
-
}
|
|
3293
|
-
/**
|
|
3294
|
-
* Validate a coding FILE: scheme-gate + fetch + parse (shared `loadYaml`), then the
|
|
3295
|
-
* pure `checkCodingValue`. The web app passes the default http(s)-only schemes; the
|
|
3296
|
-
* CLI adds `file:` so a local coding YAML on disk validates too.
|
|
3297
|
-
*/
|
|
3298
|
-
async function loadAndCheckCoding(url, fetchImpl, opts = {}) {
|
|
3299
|
-
const yaml = await loadYaml(url, fetchImpl, opts);
|
|
3300
|
-
if (!yaml.ok) return {
|
|
3301
|
-
ok: false,
|
|
3302
|
-
errors: [yaml.error],
|
|
3303
|
-
warnings: []
|
|
3304
|
-
};
|
|
3305
|
-
const valid = validate(yaml.value, CodingYamlSchema, "CODING_SCHEMA_ERROR", url);
|
|
3306
|
-
if (!valid.ok) return {
|
|
3307
|
-
ok: false,
|
|
3308
|
-
errors: [valid.error],
|
|
3309
|
-
warnings: []
|
|
3310
|
-
};
|
|
3311
|
-
const checked = checkCodingParsed(valid.data);
|
|
3312
|
-
if (!checked.ok) return checked;
|
|
3313
|
-
const assembled = await assembleFragmentPrompt({
|
|
3314
|
-
fragment_files: valid.data.fragment_files,
|
|
3315
|
-
text_files: valid.data.text_files
|
|
3316
|
-
}, url, fetchImpl, {
|
|
3317
|
-
allowedSchemes: opts.allowedSchemes,
|
|
3318
|
-
validateLibraries: opts.validateLibraries ?? true
|
|
3319
|
-
}, valid.data.instructions);
|
|
3320
|
-
const warnings = [...checked.warnings, ...assembled.warnings];
|
|
3321
|
-
if (!assembled.ok) return {
|
|
3322
|
-
ok: false,
|
|
3323
|
-
errors: assembled.errors,
|
|
3324
|
-
warnings
|
|
3325
|
-
};
|
|
3326
|
-
return {
|
|
3327
|
-
...checked,
|
|
3328
|
-
warnings
|
|
3329
|
-
};
|
|
3330
|
-
}
|
|
3331
|
-
//#endregion
|
|
3332
|
-
//#region ../lib/quiz-schema.ts
|
|
3333
|
-
/**
|
|
3334
|
-
* A live quiz include: alias + URL, mirroring `FragmentFileRefSchema` (same URL
|
|
3335
|
-
* contract). The alias prefixes every imported question id as `"<alias>/<id>"`, so
|
|
3336
|
-
* on top of the no-dot rule it may not contain a `/` either. Aliases live in their
|
|
3337
|
-
* OWN namespace (they never appear in `{{…}}` markers — only in question ids).
|
|
2962
|
+
* A live quiz include: alias + URL, mirroring `FragmentFileRefSchema` (same URL
|
|
2963
|
+
* contract). The alias prefixes every imported question id as `"<alias>/<id>"`, so
|
|
2964
|
+
* on top of the no-dot rule it may not contain a `/` either. Aliases live in their
|
|
2965
|
+
* OWN namespace (they never appear in `{{…}}` markers — only in question ids).
|
|
3338
2966
|
*/
|
|
3339
2967
|
const QuizFileRefSchema = z.strictObject({
|
|
3340
2968
|
id: z.string().regex(/^[^./]+$/, { message: "Alias must not contain a dot or a slash" }).meta({
|
|
@@ -3606,181 +3234,1655 @@ async function loadAndCheckQuiz(url, fetchImpl, opts = {}) {
|
|
|
3606
3234
|
};
|
|
3607
3235
|
}
|
|
3608
3236
|
//#endregion
|
|
3609
|
-
//#region ../lib/
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
})
|
|
3623
|
-
|
|
3624
|
-
description: "The model and provider that back the writing coach."
|
|
3625
|
-
}),
|
|
3626
|
-
fragment_files: z.array(FragmentFileRefSchema).default([]).meta({ description: "Optional fragment libraries this activity pulls shared prompt fragments from." }),
|
|
3627
|
-
text_files: z.array(TextFileRefSchema).default([]).meta({ description: "Optional plain-text files (markdown / source) embedded verbatim into instructions via {{file \"alias\"}} markers." }),
|
|
3628
|
-
instructions: z.string().min(1).meta({ description: "The writing coach's system prompt. SERVER-ONLY: never sent to the browser, so it may describe the assessment criteria and coaching strategy. When any fragment_files or text_files are declared it is a Handlebars template: place fragments inline with {{fragment \"alias.id\" …}} and embed text files with {{file \"alias\"}} (optionally {{file \"alias\" from=10 to=40}} for a line range; escape a literal {{ as \\{{)." }),
|
|
3629
|
-
placeholder: z.string().optional().meta({ description: "Optional starter text prefilled into the editor. Empty for a blank page." })
|
|
3630
|
-
});
|
|
3631
|
-
//#endregion
|
|
3632
|
-
//#region ../lib/writing-validate.ts
|
|
3633
|
-
/** Writing DIVERGES from tutor/quiz: it defaults to attributed (`anonymous: false`). */
|
|
3634
|
-
const DEFAULT_ANONYMOUS = false;
|
|
3237
|
+
//#region ../lib/eval-validate.ts
|
|
3238
|
+
function fail(errors, warnings = []) {
|
|
3239
|
+
return {
|
|
3240
|
+
ok: false,
|
|
3241
|
+
errors,
|
|
3242
|
+
warnings
|
|
3243
|
+
};
|
|
3244
|
+
}
|
|
3245
|
+
/** Zod issues as one error each, the dotted path leading the message. */
|
|
3246
|
+
function schemaErrors(issues, url) {
|
|
3247
|
+
return issues.map((issue) => {
|
|
3248
|
+
const path = issue.path.map((segment) => String(segment)).join(".");
|
|
3249
|
+
return error("EVAL_SCHEMA", path ? `${path}: ${issue.message}` : issue.message, { url });
|
|
3250
|
+
});
|
|
3251
|
+
}
|
|
3635
3252
|
/**
|
|
3636
|
-
*
|
|
3637
|
-
* `
|
|
3638
|
-
*
|
|
3253
|
+
* Check ONE eval file end to end. `fetcher` is the caller's network seam and
|
|
3254
|
+
* `allowedSchemes` the usual SSRF gate (the CLI adds `file:` so an on-disk eval
|
|
3255
|
+
* resolves the quiz sitting next to it).
|
|
3639
3256
|
*/
|
|
3640
|
-
function
|
|
3257
|
+
async function loadAndCheckEval(url, fetchImpl, opts = {}) {
|
|
3258
|
+
const allowedSchemes = opts.allowedSchemes;
|
|
3259
|
+
const yaml = await loadYaml(url, fetchImpl, { allowedSchemes });
|
|
3260
|
+
if (!yaml.ok) return fail([error(yaml.error.code === "YAML_PARSE_ERROR" ? "EVAL_PARSE" : "EVAL_READ", yaml.error.message, { url })]);
|
|
3261
|
+
const parsed = EvalYamlSchema.safeParse(yaml.value);
|
|
3262
|
+
if (!parsed.success) return fail(schemaErrors(parsed.error.issues, url));
|
|
3263
|
+
const evalFile = parsed.data;
|
|
3264
|
+
let targetUrl;
|
|
3265
|
+
try {
|
|
3266
|
+
targetUrl = new URL(evalFile.target, url).href;
|
|
3267
|
+
} catch {
|
|
3268
|
+
return fail([error("EVAL_TARGET_ERROR", `The target "${evalFile.target}" is not a usable URL.`, { url })]);
|
|
3269
|
+
}
|
|
3270
|
+
if (allowedSchemes !== void 0) {
|
|
3271
|
+
let scheme = "";
|
|
3272
|
+
try {
|
|
3273
|
+
scheme = new URL(targetUrl).protocol;
|
|
3274
|
+
} catch {
|
|
3275
|
+
scheme = "";
|
|
3276
|
+
}
|
|
3277
|
+
if (!allowedSchemes.includes(scheme)) return fail([error("EVAL_TARGET_ERROR", `The target URL is not allowed: ${targetUrl}`, { url: targetUrl })]);
|
|
3278
|
+
}
|
|
3279
|
+
const warnings = [];
|
|
3280
|
+
if (opts.strictTarget) {
|
|
3281
|
+
const strict = await loadAndCheckQuiz(targetUrl, fetchImpl, {
|
|
3282
|
+
allowedSchemes,
|
|
3283
|
+
validateLibraries: opts.validateLibraries ?? true
|
|
3284
|
+
});
|
|
3285
|
+
warnings.push(...strict.warnings);
|
|
3286
|
+
if (!strict.ok) return fail(strict.errors, warnings);
|
|
3287
|
+
}
|
|
3288
|
+
const dumped = await dumpPrompts("quiz", targetUrl, fetchImpl, { allowedSchemes });
|
|
3289
|
+
if (!dumped.ok) return fail(dumped.errors.map((e) => error("EVAL_TARGET_ERROR", `The target quiz could not be loaded: ${e.message}`, { url: targetUrl })), warnings);
|
|
3290
|
+
const quizDump = dumped.dump;
|
|
3291
|
+
if (quizDump.kind !== "quiz") return fail([error("EVAL_TARGET_ERROR", "The target is not a quiz.", { url: targetUrl })], warnings);
|
|
3292
|
+
const known = new Set(quizDump.grading.questions.map((question) => question.id));
|
|
3293
|
+
const unknown = evalFile.questions.filter((question) => !known.has(question.question)).map((question) => error("EVAL_UNKNOWN_QUESTION", `The target quiz has no question "${question.question}".`, {
|
|
3294
|
+
questionId: question.question,
|
|
3295
|
+
url: targetUrl
|
|
3296
|
+
}));
|
|
3297
|
+
if (unknown.length > 0) return fail(unknown, warnings);
|
|
3298
|
+
const resolved = await loadQuizFrom(targetUrl, fetchImpl, { allowedSchemes });
|
|
3299
|
+
const quizQuestions = resolved.ok ? resolved.quiz.questions.map((question) => ({
|
|
3300
|
+
id: question.id,
|
|
3301
|
+
text: question.question
|
|
3302
|
+
})) : [];
|
|
3641
3303
|
return {
|
|
3642
3304
|
ok: true,
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
warnings
|
|
3305
|
+
evalFile,
|
|
3306
|
+
targetUrl,
|
|
3307
|
+
quizDump,
|
|
3308
|
+
quizQuestions,
|
|
3309
|
+
caseCount: evalFile.questions.reduce((sum, question) => sum + question.answers.length, 0),
|
|
3310
|
+
warnings
|
|
3649
3311
|
};
|
|
3650
3312
|
}
|
|
3313
|
+
//#endregion
|
|
3314
|
+
//#region src/retry.ts
|
|
3315
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
3651
3316
|
/**
|
|
3652
|
-
*
|
|
3653
|
-
*
|
|
3654
|
-
*
|
|
3317
|
+
* Runs `work` up to `attempts` times, waiting a LINEARLY growing delay between tries
|
|
3318
|
+
* (the shape the Python PoC used against SCCH's occasional 504s). Returns the first
|
|
3319
|
+
* outcome `shouldRetry` rejects, or the last outcome when the budget runs out.
|
|
3655
3320
|
*/
|
|
3656
|
-
async function
|
|
3657
|
-
const
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
|
|
3321
|
+
async function withRetry(work, options) {
|
|
3322
|
+
const attempts = Math.max(1, options.attempts ?? 4);
|
|
3323
|
+
const baseDelayMs = options.baseDelayMs ?? 5e3;
|
|
3324
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
3325
|
+
let last;
|
|
3326
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
3327
|
+
if (attempt > 1) await sleep(baseDelayMs * (attempt - 1));
|
|
3328
|
+
last = await work(attempt);
|
|
3329
|
+
if (!options.shouldRetry(last)) return last;
|
|
3330
|
+
}
|
|
3331
|
+
return last;
|
|
3332
|
+
}
|
|
3333
|
+
/**
|
|
3334
|
+
* Maps `items` through `fn` with at most `limit` in flight, preserving INPUT order in
|
|
3335
|
+
* the result (a worker pool, not `Promise.all` in chunks — a slow item never stalls the
|
|
3336
|
+
* pool behind it). `fn` receives the item's original index so callers can report
|
|
3337
|
+
* progress meaningfully.
|
|
3338
|
+
*/
|
|
3339
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
3340
|
+
const results = new Array(items.length);
|
|
3341
|
+
const workers = Math.max(1, Math.min(Math.floor(limit) || 1, items.length));
|
|
3342
|
+
let next = 0;
|
|
3343
|
+
async function worker() {
|
|
3344
|
+
for (;;) {
|
|
3345
|
+
const index = next++;
|
|
3346
|
+
if (index >= items.length) return;
|
|
3347
|
+
results[index] = await fn(items[index], index);
|
|
3348
|
+
}
|
|
3349
|
+
}
|
|
3350
|
+
await Promise.all(Array.from({ length: workers }, () => worker()));
|
|
3351
|
+
return results;
|
|
3352
|
+
}
|
|
3353
|
+
//#endregion
|
|
3354
|
+
//#region src/eval-run.ts
|
|
3355
|
+
const ZERO_USAGE = {
|
|
3356
|
+
input: 0,
|
|
3357
|
+
cachedInput: 0,
|
|
3358
|
+
output: 0
|
|
3359
|
+
};
|
|
3360
|
+
/** Add one call's usage into an accumulator (mutating it — internal to the sums below). */
|
|
3361
|
+
function addUsage(total, usage) {
|
|
3362
|
+
if (!usage) return;
|
|
3363
|
+
total.input += usage.input;
|
|
3364
|
+
total.cachedInput += usage.cachedInput;
|
|
3365
|
+
total.output += usage.output;
|
|
3366
|
+
}
|
|
3367
|
+
/** Consecutive fully-errored cases that mean "the server is down, stop now". */
|
|
3368
|
+
const CIRCUIT_BREAKER_LIMIT = 3;
|
|
3369
|
+
/** Flatten questions × answers into cases, each carrying its grading prompt. */
|
|
3370
|
+
function planCases(checked) {
|
|
3371
|
+
const systemById = new Map(checked.quizDump.grading.questions.map((question) => [question.id, question.system]));
|
|
3372
|
+
const cases = [];
|
|
3373
|
+
for (const question of checked.evalFile.questions) question.answers.forEach((answer, answerIndex) => {
|
|
3374
|
+
cases.push({
|
|
3375
|
+
questionId: question.question,
|
|
3376
|
+
answerIndex,
|
|
3377
|
+
expected: normalizeExpect(answer.expect),
|
|
3378
|
+
answer: answer.answer,
|
|
3379
|
+
system: systemById.get(question.question)
|
|
3380
|
+
});
|
|
3381
|
+
});
|
|
3382
|
+
return cases;
|
|
3383
|
+
}
|
|
3384
|
+
/**
|
|
3385
|
+
* The majority verdict over the graded repeats. Returns the winner plus whether the
|
|
3386
|
+
* case PASSES: a unique majority passes when it is expected; a TIE passes only when
|
|
3387
|
+
* every tied verdict is expected (so a coin-flip between two acceptable gradings is a
|
|
3388
|
+
* pass, and one between an acceptable and an unacceptable one is not).
|
|
3389
|
+
*/
|
|
3390
|
+
function majority(graded, expected) {
|
|
3391
|
+
if (graded.length === 0) return void 0;
|
|
3392
|
+
const counts = /* @__PURE__ */ new Map();
|
|
3393
|
+
for (const verdict of graded) counts.set(verdict, (counts.get(verdict) ?? 0) + 1);
|
|
3394
|
+
const top = Math.max(...counts.values());
|
|
3395
|
+
const tied = [...counts.entries()].filter(([, count]) => count === top).map(([verdict]) => verdict).sort((a, b) => EVAL_VERDICTS.indexOf(a) - EVAL_VERDICTS.indexOf(b));
|
|
3396
|
+
return {
|
|
3397
|
+
verdict: tied[0],
|
|
3398
|
+
passed: tied.every((verdict) => expected.includes(verdict))
|
|
3662
3399
|
};
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3400
|
+
}
|
|
3401
|
+
/** The seam: one runner per eval kind (mirrors `promptDumpers`). */
|
|
3402
|
+
const evalRunners = { quiz: { async run(checked, options) {
|
|
3403
|
+
const repeats = Math.max(1, Math.floor(options.repeats ?? 1));
|
|
3404
|
+
const concurrency = Math.max(1, Math.floor(options.concurrency ?? 4));
|
|
3405
|
+
const planned = planCases(checked);
|
|
3406
|
+
const total = planned.length * repeats;
|
|
3407
|
+
const questionTexts = new Map(checked.quizQuestions.map((q) => [q.id, q.text]));
|
|
3408
|
+
let done = 0;
|
|
3409
|
+
let consecutiveErrored = 0;
|
|
3410
|
+
let aborted;
|
|
3411
|
+
const progress = () => {
|
|
3412
|
+
done += 1;
|
|
3413
|
+
options.onProgress?.({
|
|
3414
|
+
done,
|
|
3415
|
+
total
|
|
3416
|
+
});
|
|
3668
3417
|
};
|
|
3669
|
-
const
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3418
|
+
const results = await mapWithConcurrency(planned, concurrency, async (plan) => {
|
|
3419
|
+
const rows = [];
|
|
3420
|
+
for (let repeatIndex = 0; repeatIndex < repeats; repeatIndex++) {
|
|
3421
|
+
if (aborted) break;
|
|
3422
|
+
if (plan.system === void 0) {
|
|
3423
|
+
rows.push({
|
|
3424
|
+
repeatIndex,
|
|
3425
|
+
error: { message: `The quiz has no question "${plan.questionId}".` }
|
|
3426
|
+
});
|
|
3427
|
+
progress();
|
|
3428
|
+
continue;
|
|
3429
|
+
}
|
|
3430
|
+
const outcome = await withRetry(() => options.grade({
|
|
3431
|
+
system: plan.system,
|
|
3432
|
+
answer: plan.answer
|
|
3433
|
+
}), {
|
|
3434
|
+
attempts: options.retry?.attempts,
|
|
3435
|
+
baseDelayMs: options.retry?.baseDelayMs,
|
|
3436
|
+
sleep: options.retry?.sleep,
|
|
3437
|
+
shouldRetry: (value) => !value.ok && value.retryable && value.auth !== true
|
|
3438
|
+
});
|
|
3439
|
+
progress();
|
|
3440
|
+
if (outcome.ok) {
|
|
3441
|
+
rows.push({
|
|
3442
|
+
repeatIndex,
|
|
3443
|
+
got: outcome.verdict,
|
|
3444
|
+
feedback: outcome.feedback,
|
|
3445
|
+
...outcome.usage ? { usage: outcome.usage } : {}
|
|
3446
|
+
});
|
|
3447
|
+
continue;
|
|
3448
|
+
}
|
|
3449
|
+
rows.push({
|
|
3450
|
+
repeatIndex,
|
|
3451
|
+
error: outcome.error
|
|
3452
|
+
});
|
|
3453
|
+
if (outcome.auth) {
|
|
3454
|
+
aborted ??= {
|
|
3455
|
+
reason: "auth",
|
|
3456
|
+
message: "Authentication failed — the run was aborted. Run `novedu-cli login`."
|
|
3457
|
+
};
|
|
3458
|
+
break;
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
const graded = rows.flatMap((row) => row.got ? [row.got] : []);
|
|
3462
|
+
const winner = majority(graded, plan.expected);
|
|
3463
|
+
const status = rows.length === 0 ? "skipped" : !winner ? "errored" : winner.passed ? "passed" : "failed";
|
|
3464
|
+
if (status === "errored") {
|
|
3465
|
+
consecutiveErrored += 1;
|
|
3466
|
+
if (consecutiveErrored >= CIRCUIT_BREAKER_LIMIT) aborted ??= {
|
|
3467
|
+
reason: "circuit-breaker",
|
|
3468
|
+
message: `${CIRCUIT_BREAKER_LIMIT} cases failed in a row — the run was aborted.`
|
|
3469
|
+
};
|
|
3470
|
+
} else if (status !== "skipped") consecutiveErrored = 0;
|
|
3471
|
+
return {
|
|
3472
|
+
questionId: plan.questionId,
|
|
3473
|
+
answerIndex: plan.answerIndex,
|
|
3474
|
+
expected: plan.expected,
|
|
3475
|
+
answer: plan.answer,
|
|
3476
|
+
status,
|
|
3477
|
+
...winner ? { verdict: winner.verdict } : {},
|
|
3478
|
+
unstable: new Set(graded).size > 1,
|
|
3479
|
+
repeats: rows
|
|
3480
|
+
};
|
|
3481
|
+
});
|
|
3482
|
+
const usage = { ...ZERO_USAGE };
|
|
3483
|
+
for (const result of results) for (const row of result.repeats) addUsage(usage, row.usage);
|
|
3484
|
+
const totals = {
|
|
3485
|
+
cases: results.length,
|
|
3486
|
+
passed: results.filter((c) => c.status === "passed").length,
|
|
3487
|
+
failed: results.filter((c) => c.status === "failed").length,
|
|
3488
|
+
errored: results.filter((c) => c.status === "errored").length,
|
|
3489
|
+
skipped: results.filter((c) => c.status === "skipped").length,
|
|
3490
|
+
unstable: results.filter((c) => c.unstable).length,
|
|
3491
|
+
repeats,
|
|
3492
|
+
calls: total,
|
|
3493
|
+
usage
|
|
3683
3494
|
};
|
|
3495
|
+
const confusionCounts = /* @__PURE__ */ new Map();
|
|
3496
|
+
for (const result of results) {
|
|
3497
|
+
if (!result.verdict) continue;
|
|
3498
|
+
const key = `${expectedKey(result.expected)}${result.verdict}`;
|
|
3499
|
+
confusionCounts.set(key, (confusionCounts.get(key) ?? 0) + 1);
|
|
3500
|
+
}
|
|
3501
|
+
const confusion = [...confusionCounts.entries()].map(([key, count]) => {
|
|
3502
|
+
const [expected = "", got = ""] = key.split("\0");
|
|
3503
|
+
return {
|
|
3504
|
+
expected,
|
|
3505
|
+
got,
|
|
3506
|
+
count
|
|
3507
|
+
};
|
|
3508
|
+
}).sort((a, b) => a.expected.localeCompare(b.expected) || a.got.localeCompare(b.got));
|
|
3509
|
+
const strictCases = results.filter((result) => !result.expected.includes("correct"));
|
|
3510
|
+
const falseCorrectCount = strictCases.filter((result) => result.verdict === "correct").length;
|
|
3684
3511
|
return {
|
|
3685
|
-
|
|
3686
|
-
|
|
3512
|
+
id: checked.evalFile.id,
|
|
3513
|
+
target: checked.targetUrl,
|
|
3514
|
+
llm: options.llm,
|
|
3515
|
+
totals,
|
|
3516
|
+
questions: [...new Set(checked.evalFile.questions.map((question) => question.question))].map((id) => ({
|
|
3517
|
+
id,
|
|
3518
|
+
text: questionTexts.get(id) ?? ""
|
|
3519
|
+
})),
|
|
3520
|
+
mismatches: results.filter((result) => result.status === "failed" || result.status === "errored"),
|
|
3521
|
+
cases: results,
|
|
3522
|
+
confusion,
|
|
3523
|
+
falseCorrect: {
|
|
3524
|
+
count: falseCorrectCount,
|
|
3525
|
+
denominator: strictCases.length,
|
|
3526
|
+
rate: strictCases.length === 0 ? 0 : falseCorrectCount / strictCases.length
|
|
3527
|
+
},
|
|
3528
|
+
...aborted ? { aborted } : {}
|
|
3687
3529
|
};
|
|
3530
|
+
} } };
|
|
3531
|
+
/** Run ONE checked eval file — the single entry point the command uses. */
|
|
3532
|
+
function runEval(kind, checked, options) {
|
|
3533
|
+
return evalRunners[kind].run(checked, options);
|
|
3534
|
+
}
|
|
3535
|
+
/** One file's own verdict: valid, graded, and not a single non-passing case. */
|
|
3536
|
+
function filePassed(file) {
|
|
3537
|
+
if (file.status === "invalid" || !file.result) return false;
|
|
3538
|
+
const { failed, errored, skipped } = file.result.totals;
|
|
3539
|
+
return failed === 0 && errored === 0 && skipped === 0;
|
|
3688
3540
|
}
|
|
3689
|
-
//#endregion
|
|
3690
|
-
//#region src/commands/validate.ts
|
|
3691
|
-
/** Every kind the `--kind` flag accepts (used for the option help + guard). */
|
|
3692
|
-
const VALIDATE_KINDS = [
|
|
3693
|
-
"tutor",
|
|
3694
|
-
"fragment",
|
|
3695
|
-
"quiz",
|
|
3696
|
-
"writing",
|
|
3697
|
-
"coding"
|
|
3698
|
-
];
|
|
3699
3541
|
/**
|
|
3700
|
-
*
|
|
3701
|
-
*
|
|
3702
|
-
* absolute `file://` URL.
|
|
3542
|
+
* Grand totals across a batch. This is the ONE machine-readable shape `--json` /
|
|
3543
|
+
* `--out` emit, single file or not, so scripts never branch on the file count.
|
|
3703
3544
|
*/
|
|
3704
|
-
function
|
|
3705
|
-
|
|
3706
|
-
|
|
3545
|
+
function summarizeBatch(files) {
|
|
3546
|
+
const totals = {
|
|
3547
|
+
files: files.length,
|
|
3548
|
+
invalid: files.filter((file) => file.status === "invalid").length,
|
|
3549
|
+
cases: 0,
|
|
3550
|
+
passed: 0,
|
|
3551
|
+
failed: 0,
|
|
3552
|
+
errored: 0,
|
|
3553
|
+
skipped: 0,
|
|
3554
|
+
unstable: 0,
|
|
3555
|
+
usage: { ...ZERO_USAGE }
|
|
3556
|
+
};
|
|
3557
|
+
for (const file of files) {
|
|
3558
|
+
if (!file.result) continue;
|
|
3559
|
+
totals.cases += file.result.totals.cases;
|
|
3560
|
+
totals.passed += file.result.totals.passed;
|
|
3561
|
+
totals.failed += file.result.totals.failed;
|
|
3562
|
+
totals.errored += file.result.totals.errored;
|
|
3563
|
+
totals.skipped += file.result.totals.skipped;
|
|
3564
|
+
totals.unstable += file.result.totals.unstable;
|
|
3565
|
+
addUsage(totals.usage, file.result.totals.usage);
|
|
3566
|
+
}
|
|
3567
|
+
return {
|
|
3568
|
+
files: files.map((file) => ({
|
|
3569
|
+
...file,
|
|
3570
|
+
passed: filePassed(file)
|
|
3571
|
+
})),
|
|
3572
|
+
passed: batchPassed({ totals }),
|
|
3573
|
+
totals
|
|
3574
|
+
};
|
|
3707
3575
|
}
|
|
3708
3576
|
/**
|
|
3709
|
-
* The
|
|
3710
|
-
*
|
|
3711
|
-
*
|
|
3712
|
-
* tutor path runs the THOROUGH check (`validateLibraries`), so every fragment in every
|
|
3713
|
-
* referenced library is rendered — not just the ones the tutor uses.
|
|
3577
|
+
* The CI gate: every file valid, and not a single failed, errored, or skipped CASE —
|
|
3578
|
+
* an aborted (and therefore incomplete) run must never read as a pass. The single
|
|
3579
|
+
* source of truth for the exit code AND for `EvalBatchResult.passed`.
|
|
3714
3580
|
*/
|
|
3715
|
-
function
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
}));
|
|
3735
|
-
case "coding": return loadAndCheckCoding(url, cliFetcher, { allowedSchemes }).then((result) => ({
|
|
3736
|
-
kind,
|
|
3737
|
-
result
|
|
3738
|
-
}));
|
|
3739
|
-
default: return loadAndBuildTutorPrompt(url, cliFetcher, {
|
|
3740
|
-
allowedSchemes,
|
|
3741
|
-
validateLibraries: true
|
|
3742
|
-
}).then((result) => ({
|
|
3743
|
-
kind,
|
|
3744
|
-
result
|
|
3745
|
-
}));
|
|
3581
|
+
function batchPassed(batch) {
|
|
3582
|
+
return batch.totals.invalid === 0 && batch.totals.failed === 0 && batch.totals.errored === 0 && batch.totals.skipped === 0;
|
|
3583
|
+
}
|
|
3584
|
+
//#endregion
|
|
3585
|
+
//#region src/file-fetcher.ts
|
|
3586
|
+
const cliFetcher = async (url) => {
|
|
3587
|
+
if (url.startsWith("file:")) try {
|
|
3588
|
+
const text = await readFile(fileURLToPath(url), "utf8");
|
|
3589
|
+
return {
|
|
3590
|
+
ok: true,
|
|
3591
|
+
status: 200,
|
|
3592
|
+
text: async () => text
|
|
3593
|
+
};
|
|
3594
|
+
} catch {
|
|
3595
|
+
return {
|
|
3596
|
+
ok: false,
|
|
3597
|
+
status: 404,
|
|
3598
|
+
text: async () => ""
|
|
3599
|
+
};
|
|
3746
3600
|
}
|
|
3601
|
+
return defaultFetcher(url);
|
|
3602
|
+
};
|
|
3603
|
+
//#endregion
|
|
3604
|
+
//#region src/format.ts
|
|
3605
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
3606
|
+
const paint = (code, s) => useColor ? `\x1b[${code}m${s}\x1b[0m` : s;
|
|
3607
|
+
const green = (s) => paint("32", s);
|
|
3608
|
+
const red = (s) => paint("31", s);
|
|
3609
|
+
const yellow = (s) => paint("33", s);
|
|
3610
|
+
const dim = (s) => paint("2", s);
|
|
3611
|
+
/** Append the context fields an error/warning carries, when present. */
|
|
3612
|
+
function context(item) {
|
|
3613
|
+
const parts = [];
|
|
3614
|
+
if (item.fileAlias) parts.push(`file=${item.fileAlias}`);
|
|
3615
|
+
if (item.fragmentId) parts.push(`fragment=${item.fragmentId}`);
|
|
3616
|
+
if ("questionId" in item && item.questionId) parts.push(`question=${item.questionId}`);
|
|
3617
|
+
if (item.variable) parts.push(`variable=${item.variable}`);
|
|
3618
|
+
if ("url" in item && item.url) parts.push(`url=${item.url}`);
|
|
3619
|
+
if ("expectedType" in item && item.expectedType) parts.push(`expected=${item.expectedType}`);
|
|
3620
|
+
if ("actualType" in item && item.actualType) parts.push(`actual=${item.actualType}`);
|
|
3621
|
+
return parts.length ? dim(` (${parts.join(", ")})`) : "";
|
|
3747
3622
|
}
|
|
3748
|
-
function
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
$
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3623
|
+
function renderWarnings(warnings) {
|
|
3624
|
+
return warnings.map((w) => ` ${yellow("⚠")} ${yellow(w.code)} ${w.message}${context(w)}`);
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Render each error as a line, with any flattened Zod schema-issue detail
|
|
3628
|
+
* indented beneath it — so a generic "Document does not match the expected
|
|
3629
|
+
* structure" is followed by the actual field paths (e.g. `Unrecognized key:
|
|
3630
|
+
* "nae"`), matching what the web UI shows.
|
|
3631
|
+
*/
|
|
3632
|
+
function renderErrors(errors) {
|
|
3633
|
+
const lines = [];
|
|
3634
|
+
for (const e of errors) {
|
|
3635
|
+
lines.push(` ${red("✗")} ${red(e.code)} ${e.message}${context(e)}`);
|
|
3636
|
+
if (e.zodIssues) for (const issue of formatZodIssues(e.zodIssues)) lines.push(` ${dim(issue)}`);
|
|
3637
|
+
}
|
|
3638
|
+
return lines;
|
|
3639
|
+
}
|
|
3640
|
+
function formatResult(result, source) {
|
|
3641
|
+
const lines = [];
|
|
3642
|
+
if (result.ok) {
|
|
3643
|
+
lines.push(green(`✔ Valid tutor`) + dim(` — ${source}`));
|
|
3644
|
+
lines.push(` model: ${result.model}`);
|
|
3645
|
+
lines.push(` system prompt: ${result.prompt.length} chars`);
|
|
3646
|
+
lines.push(` imageInput: ${result.imageInput} anonymous: ${result.anonymous}` + (result.exampleQuestions.length ? ` exampleQuestions: ${result.exampleQuestions.length}` : ""));
|
|
3647
|
+
if (result.tools.length) lines.push(` tools: ${result.tools.join(", ")}`);
|
|
3648
|
+
if (result.warnings.length) {
|
|
3649
|
+
lines.push("");
|
|
3650
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3651
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3768
3652
|
}
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
});
|
|
3653
|
+
return lines.join("\n");
|
|
3654
|
+
}
|
|
3655
|
+
lines.push(red(`✘ Invalid tutor`) + dim(` — ${source}`));
|
|
3656
|
+
lines.push("");
|
|
3657
|
+
lines.push(red(`${result.errors.length} error(s):`));
|
|
3658
|
+
lines.push(...renderErrors(result.errors));
|
|
3659
|
+
if (result.warnings.length) {
|
|
3660
|
+
lines.push("");
|
|
3661
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3662
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3663
|
+
}
|
|
3664
|
+
return lines.join("\n");
|
|
3774
3665
|
}
|
|
3775
|
-
/**
|
|
3776
|
-
function
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3666
|
+
/** Same renderer, for a standalone fragment-FILE check (`--kind fragment`). */
|
|
3667
|
+
function formatFragmentResult(result, source) {
|
|
3668
|
+
const lines = [];
|
|
3669
|
+
if (result.ok) {
|
|
3670
|
+
lines.push(green(`✔ Valid fragment file`) + dim(` — ${source}`));
|
|
3671
|
+
lines.push(` id: ${result.fragmentFileId}`);
|
|
3672
|
+
lines.push(` fragments: ${result.fragmentIds.length}` + (result.fragmentIds.length ? ` (${result.fragmentIds.join(", ")})` : ""));
|
|
3673
|
+
if (result.warnings.length) {
|
|
3674
|
+
lines.push("");
|
|
3675
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3676
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3677
|
+
}
|
|
3678
|
+
return lines.join("\n");
|
|
3679
|
+
}
|
|
3680
|
+
lines.push(red(`✘ Invalid fragment file`) + dim(` — ${source}`));
|
|
3681
|
+
lines.push("");
|
|
3682
|
+
lines.push(red(`${result.errors.length} error(s):`));
|
|
3683
|
+
lines.push(...renderErrors(result.errors));
|
|
3684
|
+
if (result.warnings.length) {
|
|
3685
|
+
lines.push("");
|
|
3686
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3687
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3783
3688
|
}
|
|
3689
|
+
return lines.join("\n");
|
|
3690
|
+
}
|
|
3691
|
+
/**
|
|
3692
|
+
* Shared tail for the quiz/writing renderers: on failure, the error list (with any
|
|
3693
|
+
* flattened Zod issues); plus any warnings on either branch.
|
|
3694
|
+
*/
|
|
3695
|
+
function renderFailureAndWarnings(result, label, source) {
|
|
3696
|
+
const lines = [red(`✘ Invalid ${label}`) + dim(` — ${source}`), ""];
|
|
3697
|
+
lines.push(red(`${result.errors.length} error(s):`));
|
|
3698
|
+
lines.push(...renderErrors(result.errors));
|
|
3699
|
+
if (result.warnings.length) {
|
|
3700
|
+
lines.push("");
|
|
3701
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3702
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3703
|
+
}
|
|
3704
|
+
return lines.join("\n");
|
|
3705
|
+
}
|
|
3706
|
+
/** Renderer for a quiz check (`--kind quiz`). */
|
|
3707
|
+
function formatQuizResult(result, source) {
|
|
3708
|
+
if (!result.ok) return renderFailureAndWarnings(result, "quiz", source);
|
|
3709
|
+
const lines = [green(`✔ Valid quiz`) + dim(` — ${source}`)];
|
|
3710
|
+
lines.push(` id: ${result.quizId}`);
|
|
3711
|
+
lines.push(` model: ${result.model}`);
|
|
3712
|
+
lines.push(` questions: ${result.questionCount} anonymous: ${result.anonymous}`);
|
|
3713
|
+
if (result.warnings.length) {
|
|
3714
|
+
lines.push("");
|
|
3715
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3716
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3717
|
+
}
|
|
3718
|
+
return lines.join("\n");
|
|
3719
|
+
}
|
|
3720
|
+
/** Renderer for a writing-activity check (`--kind writing`). */
|
|
3721
|
+
function formatWritingResult(result, source) {
|
|
3722
|
+
if (!result.ok) return renderFailureAndWarnings(result, "writing activity", source);
|
|
3723
|
+
const lines = [green(`✔ Valid writing activity`) + dim(` — ${source}`)];
|
|
3724
|
+
lines.push(` id: ${result.writingId}`);
|
|
3725
|
+
lines.push(` model: ${result.model}`);
|
|
3726
|
+
lines.push(` anonymous: ${result.anonymous}`);
|
|
3727
|
+
if (result.warnings.length) {
|
|
3728
|
+
lines.push("");
|
|
3729
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3730
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3731
|
+
}
|
|
3732
|
+
return lines.join("\n");
|
|
3733
|
+
}
|
|
3734
|
+
/**
|
|
3735
|
+
* Renderer for a coding-activity check (`--kind coding`). Coding is ALWAYS anonymous
|
|
3736
|
+
* (the API path carries no per-student identity), so — unlike quiz/writing — that is
|
|
3737
|
+
* shown as a fixed note, not a per-file value.
|
|
3738
|
+
*/
|
|
3739
|
+
function formatCodingResult(result, source) {
|
|
3740
|
+
if (!result.ok) return renderFailureAndWarnings(result, "coding activity", source);
|
|
3741
|
+
const lines = [green(`✔ Valid coding activity`) + dim(` — ${source}`)];
|
|
3742
|
+
lines.push(` id: ${result.codingId}`);
|
|
3743
|
+
lines.push(` model: ${result.model}`);
|
|
3744
|
+
lines.push(` anonymous: true ${dim("(always — the API path carries no identity)")}`);
|
|
3745
|
+
if (result.warnings.length) {
|
|
3746
|
+
lines.push("");
|
|
3747
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3748
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3749
|
+
}
|
|
3750
|
+
return lines.join("\n");
|
|
3751
|
+
}
|
|
3752
|
+
/**
|
|
3753
|
+
* Renderer for a golden-answer eval check (`--kind eval`). An eval describes a quiz it
|
|
3754
|
+
* does not contain, so the summary names the resolved target and the size of the run
|
|
3755
|
+
* the file would produce.
|
|
3756
|
+
*/
|
|
3757
|
+
function formatEvalResult(result, source) {
|
|
3758
|
+
if (!result.ok) return renderFailureAndWarnings(result, "eval", source);
|
|
3759
|
+
const lines = [green(`✔ Valid eval`) + dim(` — ${source}`)];
|
|
3760
|
+
lines.push(` id: ${result.evalFile.id}`);
|
|
3761
|
+
lines.push(` target: ${result.targetUrl}`);
|
|
3762
|
+
lines.push(` questions: ${result.evalFile.questions.length} cases: ${result.caseCount}`);
|
|
3763
|
+
lines.push(` quiz model: ${result.quizDump.llm.provider} / ${result.quizDump.llm.model}`);
|
|
3764
|
+
if (result.warnings.length) {
|
|
3765
|
+
lines.push("");
|
|
3766
|
+
lines.push(yellow(`${result.warnings.length} warning(s):`));
|
|
3767
|
+
lines.push(...renderWarnings(result.warnings));
|
|
3768
|
+
}
|
|
3769
|
+
return lines.join("\n");
|
|
3770
|
+
}
|
|
3771
|
+
/** One-line answer snippet for a mismatch line (single-line, bounded). */
|
|
3772
|
+
function snippet(text, max = 60) {
|
|
3773
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
3774
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
|
|
3775
|
+
}
|
|
3776
|
+
/** Thousands-separated, en-US so a report reads the same on every machine. */
|
|
3777
|
+
function formatTokenCount(count) {
|
|
3778
|
+
return count.toLocaleString("en-US");
|
|
3779
|
+
}
|
|
3780
|
+
/**
|
|
3781
|
+
* `tokens: 15,420 in (12,300 cached) / 2,810 out` — or `undefined` when nothing was
|
|
3782
|
+
* reported at all (no server usage, or none of the calls succeeded), in which case the
|
|
3783
|
+
* reports print no token line rather than a misleading row of zeros. The cached
|
|
3784
|
+
* parenthetical is dropped when the provider reported no cache reads. Counts SUCCESSFUL
|
|
3785
|
+
* grading calls only, so it is a lower bound (docs/cli-eval.md).
|
|
3786
|
+
*/
|
|
3787
|
+
function formatUsageLine(usage) {
|
|
3788
|
+
if (usage.input === 0 && usage.cachedInput === 0 && usage.output === 0) return void 0;
|
|
3789
|
+
const cached = usage.cachedInput ? ` (${formatTokenCount(usage.cachedInput)} cached)` : "";
|
|
3790
|
+
return `tokens: ${formatTokenCount(usage.input)} in${cached} / ${formatTokenCount(usage.output)} out`;
|
|
3791
|
+
}
|
|
3792
|
+
/** `question#index expected … got … "answer…"` — one line per non-passing case. */
|
|
3793
|
+
function mismatchLines(result) {
|
|
3794
|
+
return result.mismatches.map((c) => {
|
|
3795
|
+
const head = `${c.questionId}#${c.answerIndex}`;
|
|
3796
|
+
const expected = c.expected.join("|");
|
|
3797
|
+
if (c.status === "errored") {
|
|
3798
|
+
const first = c.repeats.find((row) => row.error !== void 0)?.error;
|
|
3799
|
+
const message = typeof first === "object" && first !== null && "message" in first ? String(first.message) : "no verdict";
|
|
3800
|
+
return ` ${red("✗")} ${head} expected ${expected} got ${red("error")} ${dim(message)}`;
|
|
3801
|
+
}
|
|
3802
|
+
return ` ${red("✗")} ${head} expected ${expected} got ${red(c.verdict ?? "?")}` + dim(` "${snippet(c.answer)}"`);
|
|
3803
|
+
});
|
|
3804
|
+
}
|
|
3805
|
+
/**
|
|
3806
|
+
* The human report for ONE eval run: header (id, target, the EFFECTIVE llm — rendered
|
|
3807
|
+
* as `quiz-llm → override-llm` when `--llm-provider`/`--llm-model` was used, so a
|
|
3808
|
+
* comparison report can never be mistaken for a baseline one), one line per
|
|
3809
|
+
* mismatch/error, totals, the confusion matrix and the false-correct rate.
|
|
3810
|
+
*/
|
|
3811
|
+
function formatEvalReport(result, source) {
|
|
3812
|
+
const { totals } = result;
|
|
3813
|
+
const lines = [
|
|
3814
|
+
(totals.failed === 0 && totals.errored === 0 && totals.skipped === 0 ? green("✔ Eval passed") : red("✘ Eval failed")) + dim(` — ${source}`),
|
|
3815
|
+
` id: ${result.id}`,
|
|
3816
|
+
` target: ${result.target}`
|
|
3817
|
+
];
|
|
3818
|
+
const llm = result.llm.overrides ? `${result.llm.overrides.provider} / ${result.llm.overrides.model} ${yellow("→")} ${result.llm.provider} / ${result.llm.model} ${yellow("(override)")}` : `${result.llm.provider} / ${result.llm.model}`;
|
|
3819
|
+
lines.push(` llm: ${llm}`);
|
|
3820
|
+
lines.push(` cases: ${totals.cases} × ${totals.repeats} repeat(s) = ${totals.calls} grading call(s)`);
|
|
3821
|
+
if (result.aborted) {
|
|
3822
|
+
lines.push("");
|
|
3823
|
+
lines.push(red(`Run aborted: ${result.aborted.message}`));
|
|
3824
|
+
}
|
|
3825
|
+
if (result.mismatches.length) {
|
|
3826
|
+
lines.push("");
|
|
3827
|
+
lines.push(red(`${result.mismatches.length} mismatch(es):`));
|
|
3828
|
+
lines.push(...mismatchLines(result));
|
|
3829
|
+
}
|
|
3830
|
+
lines.push("");
|
|
3831
|
+
lines.push(` passed: ${totals.passed} failed: ${totals.failed} errored: ${totals.errored}` + (totals.skipped ? red(` skipped: ${totals.skipped} (run aborted)`) : "") + (totals.unstable ? dim(` unstable: ${totals.unstable}`) : ""));
|
|
3832
|
+
const tokens = formatUsageLine(totals.usage);
|
|
3833
|
+
if (tokens) lines.push(dim(` ${tokens}`));
|
|
3834
|
+
if (result.confusion.length) {
|
|
3835
|
+
lines.push("");
|
|
3836
|
+
lines.push(" confusion (expected → got):");
|
|
3837
|
+
for (const row of result.confusion) lines.push(` ${row.expected} → ${row.got}: ${row.count}`);
|
|
3838
|
+
}
|
|
3839
|
+
const { count, denominator, rate } = result.falseCorrect;
|
|
3840
|
+
lines.push("");
|
|
3841
|
+
lines.push(` false-correct: ${count}/${denominator}` + (denominator ? ` (${(rate * 100).toFixed(1)}%)` : ""));
|
|
3842
|
+
return lines.join("\n");
|
|
3843
|
+
}
|
|
3844
|
+
/**
|
|
3845
|
+
* The human report for a MULTI-file run: a per-file summary table, grand totals, then
|
|
3846
|
+
* the per-file detail sections only for files that had mismatches. The confusion matrix
|
|
3847
|
+
* and false-correct rate stay per file — mixing verdicts across unrelated quizzes is
|
|
3848
|
+
* not meaningful. A single-file run keeps the plain {@link formatEvalReport}.
|
|
3849
|
+
*/
|
|
3850
|
+
function formatEvalBatchReport(batch) {
|
|
3851
|
+
const lines = [];
|
|
3852
|
+
lines.push(`Evaluated ${batch.totals.files} file(s):`);
|
|
3853
|
+
for (const file of batch.files) {
|
|
3854
|
+
const name = shortSource$1(file.source);
|
|
3855
|
+
if (file.status === "invalid" || !file.result) {
|
|
3856
|
+
lines.push(` ${red("✘")} ${name}: ${red("invalid")} (${file.errors?.length ?? 0} error(s))`);
|
|
3857
|
+
continue;
|
|
3858
|
+
}
|
|
3859
|
+
const t = file.result.totals;
|
|
3860
|
+
const mark = t.failed === 0 && t.errored === 0 && t.skipped === 0 ? green("✔") : red("✗");
|
|
3861
|
+
lines.push(` ${mark} ${name}: ${t.cases} case(s), ${t.passed} passed, ${t.failed} failed, ${t.errored} errored` + (t.skipped ? red(`, ${t.skipped} skipped`) : "") + (t.unstable ? dim(`, ${t.unstable} unstable`) : ""));
|
|
3862
|
+
}
|
|
3863
|
+
const g = batch.totals;
|
|
3864
|
+
lines.push("");
|
|
3865
|
+
lines.push(` TOTAL: ${g.cases} case(s), ${g.passed} passed, ${g.failed} failed, ${g.errored} errored` + (g.skipped ? red(`, ${g.skipped} skipped`) : "") + (g.invalid ? red(`, ${g.invalid} invalid file(s)`) : ""));
|
|
3866
|
+
const tokens = formatUsageLine(g.usage);
|
|
3867
|
+
if (tokens) lines.push(dim(` ${tokens}`));
|
|
3868
|
+
for (const file of batch.files) {
|
|
3869
|
+
if (file.status === "invalid") {
|
|
3870
|
+
lines.push("");
|
|
3871
|
+
lines.push(red(`✘ ${shortSource$1(file.source)} — not a usable eval:`));
|
|
3872
|
+
lines.push(...renderErrors(file.errors ?? []));
|
|
3873
|
+
continue;
|
|
3874
|
+
}
|
|
3875
|
+
if (!file.result || file.result.mismatches.length === 0) continue;
|
|
3876
|
+
lines.push("");
|
|
3877
|
+
lines.push(formatEvalReport(file.result, shortSource$1(file.source)));
|
|
3878
|
+
}
|
|
3879
|
+
return lines.join("\n");
|
|
3880
|
+
}
|
|
3881
|
+
/** The last path segment of a source URL — enough to tell files apart in a table. */
|
|
3882
|
+
function shortSource$1(source) {
|
|
3883
|
+
try {
|
|
3884
|
+
const { pathname } = new URL(source);
|
|
3885
|
+
return decodeURIComponent(pathname.split("/").pop() || source);
|
|
3886
|
+
} catch {
|
|
3887
|
+
return source;
|
|
3888
|
+
}
|
|
3889
|
+
}
|
|
3890
|
+
/**
|
|
3891
|
+
* Renderer for a prompt dump (`prompts`). Kind-agnostic by construction: the envelope
|
|
3892
|
+
* (kind / id / provider+model) plus one line per prompt with its character count — the
|
|
3893
|
+
* sections come from `promptSections`, so a new kind needs no change here. `--json`
|
|
3894
|
+
* carries the prompt text itself.
|
|
3895
|
+
*/
|
|
3896
|
+
function formatPromptDump(dump, sections, source) {
|
|
3897
|
+
const lines = [green(`✔ Prompts — ${dump.kind}`) + dim(` — ${source}`)];
|
|
3898
|
+
lines.push(` id: ${dump.id}`);
|
|
3899
|
+
lines.push(` provider: ${dump.llm.provider} model: ${dump.llm.model}`);
|
|
3900
|
+
if (dump.kind === "tutor" && dump.tools.length > 0) lines.push(` tools: ${dump.tools.join(", ")}`);
|
|
3901
|
+
lines.push(` prompts: ${sections.length}`);
|
|
3902
|
+
for (const section of sections) lines.push(` ${section.name}: ${section.text.length} chars`);
|
|
3903
|
+
lines.push("");
|
|
3904
|
+
lines.push(dim(" Run again with --json for the full prompt text."));
|
|
3905
|
+
return lines.join("\n");
|
|
3906
|
+
}
|
|
3907
|
+
//#endregion
|
|
3908
|
+
//#region src/report-md.ts
|
|
3909
|
+
/** `2026-08-08 14:32 UTC` — UTC always, so two reports are comparable across machines. */
|
|
3910
|
+
function timestamp(at) {
|
|
3911
|
+
return `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
3912
|
+
}
|
|
3913
|
+
/** Thousands-separated, en-US so the report reads the same on every machine. */
|
|
3914
|
+
function count(value) {
|
|
3915
|
+
return value.toLocaleString("en-US");
|
|
3916
|
+
}
|
|
3917
|
+
/**
|
|
3918
|
+
* A teacher-authored string made safe for a TABLE CELL: newlines collapse to spaces
|
|
3919
|
+
* (a raw newline would end the row) and pipes are escaped (they would split it).
|
|
3920
|
+
*/
|
|
3921
|
+
function cell(text) {
|
|
3922
|
+
return text.replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
|
|
3923
|
+
}
|
|
3924
|
+
/** The same neutralization for a LIST ITEM, where only the newline is structural. */
|
|
3925
|
+
function inline(text) {
|
|
3926
|
+
return text.replace(/\s+/g, " ").trim();
|
|
3927
|
+
}
|
|
3928
|
+
/**
|
|
3929
|
+
* A verbatim blockquote: every line prefixed, so the text keeps its own line breaks and
|
|
3930
|
+
* can never escape into the surrounding document structure.
|
|
3931
|
+
*/
|
|
3932
|
+
function quote(text) {
|
|
3933
|
+
return text.replace(/\s+$/, "").split(/\r?\n/).map((line) => line ? `> ${line}` : ">").join("\n");
|
|
3934
|
+
}
|
|
3935
|
+
/** `SCCH / gemma-4`, or `SCCH / gemma-4 → Azure Foundry / gpt-5-mini (override)`. */
|
|
3936
|
+
function llmText(llm) {
|
|
3937
|
+
const effective = `${llm.provider} / ${llm.model}`;
|
|
3938
|
+
return llm.overrides ? `${llm.overrides.provider} / ${llm.overrides.model} → ${effective} (override)` : effective;
|
|
3939
|
+
}
|
|
3940
|
+
/** `15,420 / 12,300 / 2,810`, or an em dash when nothing was reported. */
|
|
3941
|
+
function usageCell(usage) {
|
|
3942
|
+
if (usage.input === 0 && usage.cachedInput === 0 && usage.output === 0) return "—";
|
|
3943
|
+
return `${count(usage.input)} / ${count(usage.cachedInput)} / ${count(usage.output)}`;
|
|
3944
|
+
}
|
|
3945
|
+
/** The last path segment of a source URL — how a file is named throughout the report. */
|
|
3946
|
+
function shortSource(source) {
|
|
3947
|
+
try {
|
|
3948
|
+
const { pathname } = new URL(source);
|
|
3949
|
+
return decodeURIComponent(pathname.split("/").pop() || source);
|
|
3950
|
+
} catch {
|
|
3951
|
+
return source;
|
|
3952
|
+
}
|
|
3953
|
+
}
|
|
3954
|
+
/** `1/12 (8.3%)` — the false-correct rate, or `0/0` when nothing could be false-correct. */
|
|
3955
|
+
function falseCorrectCell(result) {
|
|
3956
|
+
const { count: hits, denominator, rate } = result.falseCorrect;
|
|
3957
|
+
return denominator === 0 ? `${hits}/0` : `${hits}/${denominator} (${(rate * 100).toFixed(1)}%)`;
|
|
3958
|
+
}
|
|
3959
|
+
const OVERVIEW_HEADER = [
|
|
3960
|
+
"File",
|
|
3961
|
+
"Eval",
|
|
3962
|
+
"Cases",
|
|
3963
|
+
"Passed",
|
|
3964
|
+
"Failed",
|
|
3965
|
+
"Errored",
|
|
3966
|
+
"Skipped",
|
|
3967
|
+
"Unstable",
|
|
3968
|
+
"False-correct",
|
|
3969
|
+
"Tokens (in / cached / out)"
|
|
3970
|
+
];
|
|
3971
|
+
/** `| a | b |` for one row of the overview table. */
|
|
3972
|
+
function row(cells) {
|
|
3973
|
+
return `| ${cells.join(" | ")} |`;
|
|
3974
|
+
}
|
|
3975
|
+
/** The overview table: one row per file, plus a grand TOTAL row for a real batch. */
|
|
3976
|
+
function overview(batch) {
|
|
3977
|
+
const lines = [row(OVERVIEW_HEADER), row([
|
|
3978
|
+
"---",
|
|
3979
|
+
"---",
|
|
3980
|
+
"---:",
|
|
3981
|
+
"---:",
|
|
3982
|
+
"---:",
|
|
3983
|
+
"---:",
|
|
3984
|
+
"---:",
|
|
3985
|
+
"---:",
|
|
3986
|
+
"---:",
|
|
3987
|
+
"---:"
|
|
3988
|
+
])];
|
|
3989
|
+
for (const file of batch.files) {
|
|
3990
|
+
const name = cell(shortSource(file.source));
|
|
3991
|
+
if (!file.result) {
|
|
3992
|
+
lines.push(row([
|
|
3993
|
+
name,
|
|
3994
|
+
"**invalid**",
|
|
3995
|
+
"—",
|
|
3996
|
+
"—",
|
|
3997
|
+
"—",
|
|
3998
|
+
"—",
|
|
3999
|
+
"—",
|
|
4000
|
+
"—",
|
|
4001
|
+
"—",
|
|
4002
|
+
"—"
|
|
4003
|
+
]));
|
|
4004
|
+
continue;
|
|
4005
|
+
}
|
|
4006
|
+
const t = file.result.totals;
|
|
4007
|
+
lines.push(row([
|
|
4008
|
+
`${file.passed ? "✅" : "❌"} ${name}`,
|
|
4009
|
+
`\`${cell(file.result.id)}\``,
|
|
4010
|
+
count(t.cases),
|
|
4011
|
+
count(t.passed),
|
|
4012
|
+
count(t.failed),
|
|
4013
|
+
count(t.errored),
|
|
4014
|
+
count(t.skipped),
|
|
4015
|
+
count(t.unstable),
|
|
4016
|
+
falseCorrectCell(file.result),
|
|
4017
|
+
usageCell(t.usage)
|
|
4018
|
+
]));
|
|
4019
|
+
}
|
|
4020
|
+
if (batch.files.length > 1) {
|
|
4021
|
+
const g = batch.totals;
|
|
4022
|
+
lines.push(row([
|
|
4023
|
+
"**TOTAL**",
|
|
4024
|
+
g.invalid ? `${count(g.invalid)} invalid` : "",
|
|
4025
|
+
`**${count(g.cases)}**`,
|
|
4026
|
+
`**${count(g.passed)}**`,
|
|
4027
|
+
`**${count(g.failed)}**`,
|
|
4028
|
+
`**${count(g.errored)}**`,
|
|
4029
|
+
`**${count(g.skipped)}**`,
|
|
4030
|
+
`**${count(g.unstable)}**`,
|
|
4031
|
+
"",
|
|
4032
|
+
`**${usageCell(g.usage)}**`
|
|
4033
|
+
]));
|
|
4034
|
+
}
|
|
4035
|
+
return lines;
|
|
4036
|
+
}
|
|
4037
|
+
/** The one-line error message an errored repeat row carries. */
|
|
4038
|
+
function errorMessage(error) {
|
|
4039
|
+
if (typeof error === "string") return error;
|
|
4040
|
+
if (typeof error === "object" && error !== null && "message" in error) return String(error.message);
|
|
4041
|
+
return JSON.stringify(error ?? null);
|
|
4042
|
+
}
|
|
4043
|
+
/** `expected correct, got incorrect` — the heading's verdict half. */
|
|
4044
|
+
function verdictSummary(evalCase) {
|
|
4045
|
+
return `expected ${evalCase.expected.join(" | ")}, got ${evalCase.status === "errored" ? "error" : evalCase.verdict ?? "no verdict"}`;
|
|
4046
|
+
}
|
|
4047
|
+
/** Whether a case belongs in the details section at all (§ details only for problems). */
|
|
4048
|
+
function needsDetail(evalCase) {
|
|
4049
|
+
return evalCase.status === "failed" || evalCase.status === "errored" || evalCase.unstable;
|
|
4050
|
+
}
|
|
4051
|
+
/**
|
|
4052
|
+
* One case's section: the question it belongs to, the golden answer, and what the
|
|
4053
|
+
* grader said — plus every repeat when they disagreed (the `--repeats` signal is
|
|
4054
|
+
* exactly what a teacher wants to read here, not a majority hidden behind one line).
|
|
4055
|
+
*/
|
|
4056
|
+
function caseSection(evalCase, questionText) {
|
|
4057
|
+
const lines = [];
|
|
4058
|
+
const unstable = evalCase.unstable ? " *(unstable)*" : "";
|
|
4059
|
+
lines.push(`### \`${evalCase.questionId}\` #${evalCase.answerIndex} — ${verdictSummary(evalCase)}${unstable}`);
|
|
4060
|
+
lines.push("");
|
|
4061
|
+
if (questionText) {
|
|
4062
|
+
lines.push("**Question**");
|
|
4063
|
+
lines.push("");
|
|
4064
|
+
lines.push(quote(questionText));
|
|
4065
|
+
lines.push("");
|
|
4066
|
+
}
|
|
4067
|
+
lines.push("**Golden answer**");
|
|
4068
|
+
lines.push("");
|
|
4069
|
+
lines.push(quote(evalCase.answer));
|
|
4070
|
+
lines.push("");
|
|
4071
|
+
const graded = evalCase.repeats.filter((r) => r.got !== void 0);
|
|
4072
|
+
const disagreed = new Set(graded.map((r) => r.got)).size > 1;
|
|
4073
|
+
if (evalCase.repeats.length > 1 && (disagreed || graded.length !== evalCase.repeats.length)) {
|
|
4074
|
+
lines.push("**Repeats**");
|
|
4075
|
+
lines.push("");
|
|
4076
|
+
for (const repeat of evalCase.repeats) {
|
|
4077
|
+
const verdict = repeat.got ? `\`${repeat.got}\`` : "**error**";
|
|
4078
|
+
const detail = repeat.got ? inline(repeat.feedback ?? "") : inline(errorMessage(repeat.error));
|
|
4079
|
+
lines.push(`- #${repeat.repeatIndex + 1} — ${verdict}${detail ? ` — ${detail}` : ""}`);
|
|
4080
|
+
}
|
|
4081
|
+
lines.push("");
|
|
4082
|
+
return lines;
|
|
4083
|
+
}
|
|
4084
|
+
const feedback = graded.find((r) => r.feedback)?.feedback;
|
|
4085
|
+
if (feedback) {
|
|
4086
|
+
lines.push("**Grader feedback**");
|
|
4087
|
+
lines.push("");
|
|
4088
|
+
lines.push(quote(feedback));
|
|
4089
|
+
lines.push("");
|
|
4090
|
+
}
|
|
4091
|
+
const failure = evalCase.repeats.find((r) => r.error !== void 0);
|
|
4092
|
+
if (failure) {
|
|
4093
|
+
lines.push("**Error**");
|
|
4094
|
+
lines.push("");
|
|
4095
|
+
lines.push(quote(errorMessage(failure.error)));
|
|
4096
|
+
lines.push("");
|
|
4097
|
+
}
|
|
4098
|
+
return lines;
|
|
4099
|
+
}
|
|
4100
|
+
/** One file's details section, or `[]` when the file has nothing to report. */
|
|
4101
|
+
function fileDetails(file) {
|
|
4102
|
+
const name = shortSource(file.source);
|
|
4103
|
+
if (!file.result) {
|
|
4104
|
+
const errors = file.errors ?? [];
|
|
4105
|
+
return [
|
|
4106
|
+
`## ${cell(name)} — invalid`,
|
|
4107
|
+
"",
|
|
4108
|
+
"This file was not graded; fix the problems below and run it again.",
|
|
4109
|
+
"",
|
|
4110
|
+
...errors.map((issue) => `- \`${cell(issue.code)}\` — ${inline(issue.message)}`),
|
|
4111
|
+
""
|
|
4112
|
+
];
|
|
4113
|
+
}
|
|
4114
|
+
const result = file.result;
|
|
4115
|
+
const detailed = result.cases.filter(needsDetail);
|
|
4116
|
+
const skipped = result.totals.skipped;
|
|
4117
|
+
if (detailed.length === 0 && skipped === 0 && !result.aborted) return [];
|
|
4118
|
+
const questionText = new Map(result.questions.map((question) => [question.id, question.text]));
|
|
4119
|
+
const lines = [`## ${cell(name)} — \`${cell(result.id)}\``, ""];
|
|
4120
|
+
if (result.aborted) {
|
|
4121
|
+
lines.push("> [!WARNING]");
|
|
4122
|
+
lines.push(`> The run was aborted: ${inline(result.aborted.message)}`);
|
|
4123
|
+
lines.push("");
|
|
4124
|
+
}
|
|
4125
|
+
for (const evalCase of detailed) lines.push(...caseSection(evalCase, questionText.get(evalCase.questionId)));
|
|
4126
|
+
if (skipped > 0) {
|
|
4127
|
+
const reason = result.aborted ? ` (${inline(result.aborted.message)})` : "";
|
|
4128
|
+
lines.push(`**${count(skipped)} case(s) were never attempted**${reason} — the run is incomplete, so it cannot pass.`);
|
|
4129
|
+
lines.push("");
|
|
4130
|
+
}
|
|
4131
|
+
return lines;
|
|
4132
|
+
}
|
|
4133
|
+
/**
|
|
4134
|
+
* Render the whole run as Markdown: verdict headline, the run's facts, the overview
|
|
4135
|
+
* table, then the details of everything that needs a teacher's attention.
|
|
4136
|
+
*/
|
|
4137
|
+
function renderEvalMarkdownReport(batch, meta) {
|
|
4138
|
+
const lines = [];
|
|
4139
|
+
lines.push(`# Eval report — ${batch.passed ? "✅ passed" : "❌ failed"}`);
|
|
4140
|
+
lines.push("");
|
|
4141
|
+
lines.push(`- **Generated** ${timestamp(meta.generatedAt)} · novedu-cli ${meta.cliVersion}`);
|
|
4142
|
+
const llms = [...new Set(batch.files.filter((f) => f.result).map((f) => llmText(f.result.llm)))];
|
|
4143
|
+
for (const llm of llms) lines.push(`- **LLM** ${llm}`);
|
|
4144
|
+
lines.push(`- **Run** ${count(batch.totals.files)} file(s), ${count(batch.totals.cases)} case(s) × ${count(meta.repeats)} repeat(s), concurrency ${count(meta.concurrency)}`);
|
|
4145
|
+
const tokens = batch.totals.usage;
|
|
4146
|
+
if (tokens.input || tokens.cachedInput || tokens.output) lines.push(`- **Tokens** ${count(tokens.input)} in (${count(tokens.cachedInput)} cached) / ${count(tokens.output)} out — successful grading calls only, so a lower bound`);
|
|
4147
|
+
lines.push("");
|
|
4148
|
+
if (batch.files.filter((file) => file.result?.aborted).length > 0) {
|
|
4149
|
+
lines.push("> [!WARNING]");
|
|
4150
|
+
lines.push(`> The run was ABORTED — ${count(batch.totals.skipped)} case(s) were never graded, so this report is incomplete.`);
|
|
4151
|
+
lines.push("");
|
|
4152
|
+
}
|
|
4153
|
+
lines.push("## Overview");
|
|
4154
|
+
lines.push("");
|
|
4155
|
+
lines.push(...overview(batch));
|
|
4156
|
+
lines.push("");
|
|
4157
|
+
const details = batch.files.flatMap((file) => fileDetails(file));
|
|
4158
|
+
if (details.length === 0) {
|
|
4159
|
+
lines.push("_Nothing else to report — every case matched its expected verdict. The `--json` report carries every case, including the passing ones._");
|
|
4160
|
+
lines.push("");
|
|
4161
|
+
} else {
|
|
4162
|
+
lines.push("_Below: only the mismatched, errored and unstable cases. Passing cases live in the `--json` report._");
|
|
4163
|
+
lines.push("");
|
|
4164
|
+
lines.push(...details);
|
|
4165
|
+
}
|
|
4166
|
+
return `${lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd()}\n`;
|
|
4167
|
+
}
|
|
4168
|
+
//#endregion
|
|
4169
|
+
//#region src/version.ts
|
|
4170
|
+
let cached;
|
|
4171
|
+
/** The `version` field of the CLI's package.json; `"unknown"` if it cannot be read. */
|
|
4172
|
+
function cliVersion() {
|
|
4173
|
+
if (cached !== void 0) return cached;
|
|
4174
|
+
try {
|
|
4175
|
+
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
4176
|
+
cached = version ?? "unknown";
|
|
4177
|
+
} catch {
|
|
4178
|
+
cached = "unknown";
|
|
4179
|
+
}
|
|
4180
|
+
return cached;
|
|
4181
|
+
}
|
|
4182
|
+
//#endregion
|
|
4183
|
+
//#region ../lib/coding-schema.ts
|
|
4184
|
+
const CodingYamlSchema = z.strictObject({
|
|
4185
|
+
id: z.string().min(1).meta({ description: "Short machine-readable activity id, e.g. beginner-typescript." }),
|
|
4186
|
+
name: z.string().optional().meta({ description: "Optional human-readable label (not shown to the student)." }),
|
|
4187
|
+
title: z.string().optional().meta({ description: "Optional label shown to the student on the /<code> connection page." }),
|
|
4188
|
+
llm: z.strictObject({
|
|
4189
|
+
model: z.string().min(1).meta({ description: "The model that answers. SERVER-ONLY and PINNED: the proxy always uses this model and ignores whatever model the coding agent sends." }),
|
|
4190
|
+
provider: providerSchema
|
|
4191
|
+
}).meta({
|
|
4192
|
+
id: "llm",
|
|
4193
|
+
description: "The pinned model and provider that answer coding requests."
|
|
4194
|
+
}),
|
|
4195
|
+
fragment_files: z.array(FragmentFileRefSchema).default([]).meta({ description: "Optional fragment libraries this activity pulls shared prompt fragments from." }),
|
|
4196
|
+
text_files: z.array(TextFileRefSchema).default([]).meta({ description: "Optional plain-text files (markdown / source, e.g. a sample solution) embedded verbatim into instructions via {{file \"alias\"}} markers." }),
|
|
4197
|
+
instructions: z.string().min(1).meta({ description: "The assistant's system prompt. SERVER-ONLY: never sent to the browser or the coding agent, and appended AFTER the coding tool's own prompt (so the teacher has the final word). Constrain the assistant to what your class has learned. When any fragment_files or text_files are declared it is a Handlebars template: place fragments inline with {{fragment \"alias.id\" …}} and embed text files with {{file \"alias\"}} (optionally {{file \"alias\" from=10 to=40}} for a line range; escape a literal {{ as \\{{)." })
|
|
4198
|
+
});
|
|
4199
|
+
//#endregion
|
|
4200
|
+
//#region ../lib/coding-validate.ts
|
|
4201
|
+
/**
|
|
4202
|
+
* Extract metadata from an already-schema-validated coding value. Split from
|
|
4203
|
+
* `checkCodingValue` so `loadAndCheckCoding` can reuse the single `validate` it already
|
|
4204
|
+
* ran (no second parse of the same document against the same schema).
|
|
4205
|
+
*/
|
|
4206
|
+
function checkCodingParsed(coding) {
|
|
4207
|
+
return {
|
|
4208
|
+
ok: true,
|
|
4209
|
+
codingId: coding.id,
|
|
4210
|
+
model: coding.llm.model,
|
|
4211
|
+
provider: coding.llm.provider,
|
|
4212
|
+
title: coding.title ?? null,
|
|
4213
|
+
warnings: []
|
|
4214
|
+
};
|
|
4215
|
+
}
|
|
4216
|
+
/**
|
|
4217
|
+
* Validate a coding FILE: scheme-gate + fetch + parse (shared `loadYaml`), then the
|
|
4218
|
+
* pure `checkCodingValue`. The web app passes the default http(s)-only schemes; the
|
|
4219
|
+
* CLI adds `file:` so a local coding YAML on disk validates too.
|
|
4220
|
+
*/
|
|
4221
|
+
async function loadAndCheckCoding(url, fetchImpl, opts = {}) {
|
|
4222
|
+
const yaml = await loadYaml(url, fetchImpl, opts);
|
|
4223
|
+
if (!yaml.ok) return {
|
|
4224
|
+
ok: false,
|
|
4225
|
+
errors: [yaml.error],
|
|
4226
|
+
warnings: []
|
|
4227
|
+
};
|
|
4228
|
+
const valid = validate(yaml.value, CodingYamlSchema, "CODING_SCHEMA_ERROR", url);
|
|
4229
|
+
if (!valid.ok) return {
|
|
4230
|
+
ok: false,
|
|
4231
|
+
errors: [valid.error],
|
|
4232
|
+
warnings: []
|
|
4233
|
+
};
|
|
4234
|
+
const checked = checkCodingParsed(valid.data);
|
|
4235
|
+
if (!checked.ok) return checked;
|
|
4236
|
+
const assembled = await assembleFragmentPrompt({
|
|
4237
|
+
fragment_files: valid.data.fragment_files,
|
|
4238
|
+
text_files: valid.data.text_files
|
|
4239
|
+
}, url, fetchImpl, {
|
|
4240
|
+
allowedSchemes: opts.allowedSchemes,
|
|
4241
|
+
validateLibraries: opts.validateLibraries ?? true
|
|
4242
|
+
}, valid.data.instructions);
|
|
4243
|
+
const warnings = [...checked.warnings, ...assembled.warnings];
|
|
4244
|
+
if (!assembled.ok) return {
|
|
4245
|
+
ok: false,
|
|
4246
|
+
errors: assembled.errors,
|
|
4247
|
+
warnings
|
|
4248
|
+
};
|
|
4249
|
+
return {
|
|
4250
|
+
...checked,
|
|
4251
|
+
warnings
|
|
4252
|
+
};
|
|
4253
|
+
}
|
|
4254
|
+
//#endregion
|
|
4255
|
+
//#region ../lib/writing-schema.ts
|
|
4256
|
+
const WritingYamlSchema = z.strictObject({
|
|
4257
|
+
id: z.string().min(1).meta({ description: "Short machine-readable activity id, e.g. human-animal-short-story." }),
|
|
4258
|
+
name: z.string().optional().meta({ description: "Optional human-readable title (used as a label)." }),
|
|
4259
|
+
title: z.string().optional().meta({ description: "Optional greeting shown to students on the welcome screen instead of the default message." }),
|
|
4260
|
+
description: z.string().optional().meta({ description: "Optional description shown to students below the welcome greeting (Markdown)." }),
|
|
4261
|
+
anonymous: z.boolean().optional().meta({
|
|
4262
|
+
default: false,
|
|
4263
|
+
description: "Writing DIVERGES: it defaults to false (attributed), because review and the Save feature need to know whose text it is. Set to true for ephemeral, unattributed writing — which also disables saving."
|
|
4264
|
+
}),
|
|
4265
|
+
llm: z.strictObject({
|
|
4266
|
+
model: z.string().min(1).meta({ description: "The model that drives the feedback chat." }),
|
|
4267
|
+
provider: providerSchema
|
|
4268
|
+
}).meta({
|
|
4269
|
+
id: "llm",
|
|
4270
|
+
description: "The model and provider that back the writing coach."
|
|
4271
|
+
}),
|
|
4272
|
+
fragment_files: z.array(FragmentFileRefSchema).default([]).meta({ description: "Optional fragment libraries this activity pulls shared prompt fragments from." }),
|
|
4273
|
+
text_files: z.array(TextFileRefSchema).default([]).meta({ description: "Optional plain-text files (markdown / source) embedded verbatim into instructions via {{file \"alias\"}} markers." }),
|
|
4274
|
+
instructions: z.string().min(1).meta({ description: "The writing coach's system prompt. SERVER-ONLY: never sent to the browser, so it may describe the assessment criteria and coaching strategy. When any fragment_files or text_files are declared it is a Handlebars template: place fragments inline with {{fragment \"alias.id\" …}} and embed text files with {{file \"alias\"}} (optionally {{file \"alias\" from=10 to=40}} for a line range; escape a literal {{ as \\{{)." }),
|
|
4275
|
+
placeholder: z.string().optional().meta({ description: "Optional starter text prefilled into the editor. Empty for a blank page." })
|
|
4276
|
+
});
|
|
4277
|
+
//#endregion
|
|
4278
|
+
//#region ../lib/writing-validate.ts
|
|
4279
|
+
/** Writing DIVERGES from tutor/quiz: it defaults to attributed (`anonymous: false`). */
|
|
4280
|
+
const DEFAULT_ANONYMOUS = false;
|
|
4281
|
+
/**
|
|
4282
|
+
* Extract metadata from an already-schema-validated writing value. Split from
|
|
4283
|
+
* `checkWritingValue` so `loadAndCheckWriting` can reuse the single `validate` it already
|
|
4284
|
+
* ran (no second parse of the same document against the same schema).
|
|
4285
|
+
*/
|
|
4286
|
+
function checkWritingParsed(writing) {
|
|
4287
|
+
return {
|
|
4288
|
+
ok: true,
|
|
4289
|
+
writingId: writing.id,
|
|
4290
|
+
model: writing.llm.model,
|
|
4291
|
+
provider: writing.llm.provider,
|
|
4292
|
+
anonymous: writing.anonymous ?? DEFAULT_ANONYMOUS,
|
|
4293
|
+
title: writing.title ?? null,
|
|
4294
|
+
warnings: []
|
|
4295
|
+
};
|
|
4296
|
+
}
|
|
4297
|
+
/**
|
|
4298
|
+
* Validate a writing FILE: scheme-gate + fetch + parse (shared `loadYaml`), then the
|
|
4299
|
+
* pure `checkWritingValue`. The web app passes the default http(s)-only schemes; the
|
|
4300
|
+
* CLI adds `file:` so a local writing YAML on disk validates too.
|
|
4301
|
+
*/
|
|
4302
|
+
async function loadAndCheckWriting(url, fetchImpl, opts = {}) {
|
|
4303
|
+
const yaml = await loadYaml(url, fetchImpl, opts);
|
|
4304
|
+
if (!yaml.ok) return {
|
|
4305
|
+
ok: false,
|
|
4306
|
+
errors: [yaml.error],
|
|
4307
|
+
warnings: []
|
|
4308
|
+
};
|
|
4309
|
+
const valid = validate(yaml.value, WritingYamlSchema, "WRITING_SCHEMA_ERROR", url);
|
|
4310
|
+
if (!valid.ok) return {
|
|
4311
|
+
ok: false,
|
|
4312
|
+
errors: [valid.error],
|
|
4313
|
+
warnings: []
|
|
4314
|
+
};
|
|
4315
|
+
const checked = checkWritingParsed(valid.data);
|
|
4316
|
+
if (!checked.ok) return checked;
|
|
4317
|
+
const assembled = await assembleFragmentPrompt({
|
|
4318
|
+
fragment_files: valid.data.fragment_files,
|
|
4319
|
+
text_files: valid.data.text_files
|
|
4320
|
+
}, url, fetchImpl, {
|
|
4321
|
+
allowedSchemes: opts.allowedSchemes,
|
|
4322
|
+
validateLibraries: opts.validateLibraries ?? true
|
|
4323
|
+
}, valid.data.instructions);
|
|
4324
|
+
const warnings = [...checked.warnings, ...assembled.warnings];
|
|
4325
|
+
if (!assembled.ok) return {
|
|
4326
|
+
ok: false,
|
|
4327
|
+
errors: assembled.errors,
|
|
4328
|
+
warnings
|
|
4329
|
+
};
|
|
4330
|
+
return {
|
|
4331
|
+
...checked,
|
|
4332
|
+
warnings
|
|
4333
|
+
};
|
|
4334
|
+
}
|
|
4335
|
+
//#endregion
|
|
4336
|
+
//#region src/commands/validate.ts
|
|
4337
|
+
/** Every kind the `--kind` flag accepts (used for the option help + guard). */
|
|
4338
|
+
const VALIDATE_KINDS = [
|
|
4339
|
+
"tutor",
|
|
4340
|
+
"fragment",
|
|
4341
|
+
"quiz",
|
|
4342
|
+
"writing",
|
|
4343
|
+
"coding",
|
|
4344
|
+
"eval"
|
|
4345
|
+
];
|
|
4346
|
+
/**
|
|
4347
|
+
* Turn the CLI argument into a URL the tutor core understands: an http(s) URL is
|
|
4348
|
+
* used as-is; anything else is treated as a filesystem path and converted to an
|
|
4349
|
+
* absolute `file://` URL.
|
|
4350
|
+
*/
|
|
4351
|
+
function toUrl(pathOrUrl) {
|
|
4352
|
+
if (/^https?:\/\//i.test(pathOrUrl)) return pathOrUrl;
|
|
4353
|
+
return pathToFileURL(resolve(pathOrUrl)).href;
|
|
4354
|
+
}
|
|
4355
|
+
/**
|
|
4356
|
+
* The validate command's pure core: run the requested pipeline over a local file or
|
|
4357
|
+
* public URL. `file:` is allowed in addition to http(s) so local YAML can be
|
|
4358
|
+
* validated (the web app deliberately stays http(s)-only). As an authoring tool, the
|
|
4359
|
+
* tutor path runs the THOROUGH check (`validateLibraries`), so every fragment in every
|
|
4360
|
+
* referenced library is rendered — not just the ones the tutor uses.
|
|
4361
|
+
*/
|
|
4362
|
+
function runValidate(pathOrUrl, kind) {
|
|
4363
|
+
const url = toUrl(pathOrUrl);
|
|
4364
|
+
const allowedSchemes = [
|
|
4365
|
+
"http:",
|
|
4366
|
+
"https:",
|
|
4367
|
+
"file:"
|
|
4368
|
+
];
|
|
4369
|
+
switch (kind) {
|
|
4370
|
+
case "fragment": return loadAndCheckFragmentFile(url, cliFetcher, { allowedSchemes }).then((result) => ({
|
|
4371
|
+
kind,
|
|
4372
|
+
result
|
|
4373
|
+
}));
|
|
4374
|
+
case "quiz": return loadAndCheckQuiz(url, cliFetcher, { allowedSchemes }).then((result) => ({
|
|
4375
|
+
kind,
|
|
4376
|
+
result
|
|
4377
|
+
}));
|
|
4378
|
+
case "writing": return loadAndCheckWriting(url, cliFetcher, { allowedSchemes }).then((result) => ({
|
|
4379
|
+
kind,
|
|
4380
|
+
result
|
|
4381
|
+
}));
|
|
4382
|
+
case "coding": return loadAndCheckCoding(url, cliFetcher, { allowedSchemes }).then((result) => ({
|
|
4383
|
+
kind,
|
|
4384
|
+
result
|
|
4385
|
+
}));
|
|
4386
|
+
case "eval": return loadAndCheckEval(url, cliFetcher, {
|
|
4387
|
+
allowedSchemes,
|
|
4388
|
+
validateLibraries: true,
|
|
4389
|
+
strictTarget: true
|
|
4390
|
+
}).then((result) => ({
|
|
4391
|
+
kind,
|
|
4392
|
+
result
|
|
4393
|
+
}));
|
|
4394
|
+
default: return loadAndBuildTutorPrompt(url, cliFetcher, {
|
|
4395
|
+
allowedSchemes,
|
|
4396
|
+
validateLibraries: true
|
|
4397
|
+
}).then((result) => ({
|
|
4398
|
+
kind,
|
|
4399
|
+
result
|
|
4400
|
+
}));
|
|
4401
|
+
}
|
|
4402
|
+
}
|
|
4403
|
+
function registerValidate(program) {
|
|
4404
|
+
program.command("validate").description("Validate a tutor (default), fragment library, quiz, writing, coding or eval YAML by local path or public http(s) URL").argument("<pathOrUrl>", "path to a tutor, fragment, quiz, writing, coding or eval YAML file, or a public http(s) URL").option("--kind <kind>", `what the file is: ${VALIDATE_KINDS.map((k) => `'${k}'`).join(", ")} ('tutor' is the default)`, "tutor").option("--json", "print the raw validation result as JSON").addHelpText("after", `
|
|
4405
|
+
Examples:
|
|
4406
|
+
# Validate a tutor (also strict-renders every fragment in every referenced library)
|
|
4407
|
+
$ novedu-cli validate ./activities/tutors/my-tutor.yaml
|
|
4408
|
+
|
|
4409
|
+
# Validate a fragment library on its own
|
|
4410
|
+
$ novedu-cli validate ./activities/tutors/my-fragments.yaml --kind fragment
|
|
4411
|
+
|
|
4412
|
+
# Validate a quiz, a writing activity, or a coding activity
|
|
4413
|
+
$ novedu-cli validate ./activities/quizzes/my-quiz.yaml --kind quiz
|
|
4414
|
+
$ novedu-cli validate ./activities/writings/my-writing.yaml --kind writing
|
|
4415
|
+
$ novedu-cli validate ./activities/coding/my-coding.yaml --kind coding
|
|
4416
|
+
|
|
4417
|
+
# Validate a golden-answer eval (also strict-checks the quiz it targets)
|
|
4418
|
+
$ novedu-cli validate ./my-quiz.eval.yaml --kind eval
|
|
4419
|
+
|
|
4420
|
+
# Machine-readable output for CI
|
|
4421
|
+
$ novedu-cli validate https://example.com/tutor.yaml --json`).action(async (pathOrUrl, options) => {
|
|
4422
|
+
if (options.kind !== void 0 && !VALIDATE_KINDS.includes(options.kind)) {
|
|
4423
|
+
console.error(`Invalid --kind "${options.kind}": expected ${VALIDATE_KINDS.map((k) => `"${k}"`).join(", ")}.`);
|
|
4424
|
+
process.exitCode = 1;
|
|
4425
|
+
return;
|
|
4426
|
+
}
|
|
4427
|
+
const outcome = await runValidate(pathOrUrl, options.kind ?? "tutor");
|
|
4428
|
+
if (options.json) console.log(JSON.stringify(outcome.result, null, 2));
|
|
4429
|
+
else console.log(formatOutcome(outcome, pathOrUrl));
|
|
4430
|
+
process.exitCode = outcome.result.ok ? 0 : 1;
|
|
4431
|
+
});
|
|
4432
|
+
}
|
|
4433
|
+
/** Pick the formatter for the outcome's kind (each result type has its own renderer). */
|
|
4434
|
+
function formatOutcome(outcome, source) {
|
|
4435
|
+
switch (outcome.kind) {
|
|
4436
|
+
case "fragment": return formatFragmentResult(outcome.result, source);
|
|
4437
|
+
case "quiz": return formatQuizResult(outcome.result, source);
|
|
4438
|
+
case "writing": return formatWritingResult(outcome.result, source);
|
|
4439
|
+
case "coding": return formatCodingResult(outcome.result, source);
|
|
4440
|
+
case "eval": return formatEvalResult(outcome.result, source);
|
|
4441
|
+
default: return formatResult(outcome.result, source);
|
|
4442
|
+
}
|
|
4443
|
+
}
|
|
4444
|
+
//#endregion
|
|
4445
|
+
//#region src/commands/eval.ts
|
|
4446
|
+
const CONCURRENCY_DEFAULT = 4;
|
|
4447
|
+
/** Shell metacharacters that make a plain argument a PATTERN rather than a path. */
|
|
4448
|
+
const GLOB_MAGIC = /[*?[\]{}]/;
|
|
4449
|
+
/**
|
|
4450
|
+
* Turn the positional arguments into the list of sources to evaluate. A `file:` /
|
|
4451
|
+
* `http(s):` URL and a plain path pass through untouched (so a shell-expanded glob —
|
|
4452
|
+
* which arrives as plain paths — behaves identically); an argument carrying glob magic
|
|
4453
|
+
* is expanded relative to the cwd and sorted, which is what makes `"./**\/*.eval.yaml"`
|
|
4454
|
+
* and PowerShell/cmd work. A pattern that matches NOTHING is a hard failure: it is
|
|
4455
|
+
* almost certainly a typo, and silently evaluating zero files would exit 0.
|
|
4456
|
+
*/
|
|
4457
|
+
function expandSources(args) {
|
|
4458
|
+
const expanded = [];
|
|
4459
|
+
for (const arg of args) {
|
|
4460
|
+
if (/^(?:https?|file):/i.test(arg) || !GLOB_MAGIC.test(arg)) {
|
|
4461
|
+
expanded.push(arg);
|
|
4462
|
+
continue;
|
|
4463
|
+
}
|
|
4464
|
+
let matches;
|
|
4465
|
+
try {
|
|
4466
|
+
matches = [...globSync(arg)];
|
|
4467
|
+
} catch (error) {
|
|
4468
|
+
return {
|
|
4469
|
+
ok: false,
|
|
4470
|
+
message: `Could not expand the pattern "${arg}": ${error instanceof Error ? error.message : error}`
|
|
4471
|
+
};
|
|
4472
|
+
}
|
|
4473
|
+
if (matches.length === 0) return {
|
|
4474
|
+
ok: false,
|
|
4475
|
+
message: `The pattern "${arg}" matched no files.`
|
|
4476
|
+
};
|
|
4477
|
+
expanded.push(...matches.sort((a, b) => a.localeCompare(b)));
|
|
4478
|
+
}
|
|
4479
|
+
const sources = [];
|
|
4480
|
+
const duplicates = [];
|
|
4481
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4482
|
+
for (const entry of expanded) {
|
|
4483
|
+
const url = toUrl(entry);
|
|
4484
|
+
if (seen.has(url)) {
|
|
4485
|
+
duplicates.push(url);
|
|
4486
|
+
continue;
|
|
4487
|
+
}
|
|
4488
|
+
seen.add(url);
|
|
4489
|
+
sources.push(url);
|
|
4490
|
+
}
|
|
4491
|
+
return {
|
|
4492
|
+
ok: true,
|
|
4493
|
+
sources,
|
|
4494
|
+
duplicates
|
|
4495
|
+
};
|
|
4496
|
+
}
|
|
4497
|
+
/** The `--llm-provider`/`--llm-model` pair: strictly both-or-nothing, provider checked. */
|
|
4498
|
+
function parseOverride(options) {
|
|
4499
|
+
const { llmProvider, llmModel } = options;
|
|
4500
|
+
if (llmProvider === void 0 && llmModel === void 0) return { ok: true };
|
|
4501
|
+
if (llmProvider === void 0 || llmModel === void 0) return {
|
|
4502
|
+
ok: false,
|
|
4503
|
+
message: "Pass --llm-provider and --llm-model together, or neither."
|
|
4504
|
+
};
|
|
4505
|
+
if (!LLM_PROVIDERS.includes(llmProvider)) return {
|
|
4506
|
+
ok: false,
|
|
4507
|
+
message: `Unknown --llm-provider "${llmProvider}": expected ${LLM_PROVIDERS.map((p) => `"${p}"`).join(" or ")}.`
|
|
4508
|
+
};
|
|
4509
|
+
return {
|
|
4510
|
+
ok: true,
|
|
4511
|
+
llm: {
|
|
4512
|
+
provider: llmProvider,
|
|
4513
|
+
model: llmModel
|
|
4514
|
+
}
|
|
4515
|
+
};
|
|
4516
|
+
}
|
|
4517
|
+
/**
|
|
4518
|
+
* The optional `usage: { input, cachedInput, output }` of a 200 response, defensively:
|
|
4519
|
+
* anything that is not three finite numbers is simply absent (an older server, or one
|
|
4520
|
+
* whose provider reports nothing, must never break a run).
|
|
4521
|
+
*/
|
|
4522
|
+
function parseUsage(value) {
|
|
4523
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
4524
|
+
const { input, cachedInput, output } = value;
|
|
4525
|
+
const counts = [
|
|
4526
|
+
input,
|
|
4527
|
+
cachedInput,
|
|
4528
|
+
output
|
|
4529
|
+
].map((count) => typeof count === "number" && Number.isFinite(count) ? Math.max(0, count) : void 0);
|
|
4530
|
+
if (counts.some((count) => count === void 0)) return void 0;
|
|
4531
|
+
const [inputCount = 0, cachedCount = 0, outputCount = 0] = counts;
|
|
4532
|
+
return {
|
|
4533
|
+
input: inputCount,
|
|
4534
|
+
cachedInput: cachedCount,
|
|
4535
|
+
output: outputCount
|
|
4536
|
+
};
|
|
4537
|
+
}
|
|
4538
|
+
/**
|
|
4539
|
+
* The HTTP seam for ONE grading call, with the run's effective llm closed in — so the
|
|
4540
|
+
* runner itself never learns whether the pair came from the quiz or from `--llm-*`.
|
|
4541
|
+
* Classifies the failure for the retry policy: 5xx and true network failures are
|
|
4542
|
+
* retryable, auth failures abort the run, every other 4xx is terminal.
|
|
4543
|
+
*/
|
|
4544
|
+
function makeGradeFn(server, llm) {
|
|
4545
|
+
return async ({ system, answer }) => {
|
|
4546
|
+
const response = await performApiRequest({
|
|
4547
|
+
server,
|
|
4548
|
+
path: "/api/eval/grade",
|
|
4549
|
+
method: "POST",
|
|
4550
|
+
body: {
|
|
4551
|
+
llm,
|
|
4552
|
+
system,
|
|
4553
|
+
answer
|
|
4554
|
+
},
|
|
4555
|
+
quiet: true
|
|
4556
|
+
});
|
|
4557
|
+
if (response.ok) {
|
|
4558
|
+
const payload = response.payload;
|
|
4559
|
+
const verdict = payload?.result;
|
|
4560
|
+
if (verdict === "correct" || verdict === "partial" || verdict === "incorrect") {
|
|
4561
|
+
const usage = parseUsage(payload?.usage);
|
|
4562
|
+
return {
|
|
4563
|
+
ok: true,
|
|
4564
|
+
verdict,
|
|
4565
|
+
feedback: typeof payload?.feedback === "string" ? payload.feedback : "",
|
|
4566
|
+
...usage ? { usage } : {}
|
|
4567
|
+
};
|
|
4568
|
+
}
|
|
4569
|
+
return {
|
|
4570
|
+
ok: false,
|
|
4571
|
+
retryable: false,
|
|
4572
|
+
error: { message: "The server's response is not a grading verdict — it may not offer /api/eval/grade at all (does it run a Novedu version with the eval feature?). Check the target server, e.g. --server http://localhost:3000." }
|
|
4573
|
+
};
|
|
4574
|
+
}
|
|
4575
|
+
return {
|
|
4576
|
+
ok: false,
|
|
4577
|
+
retryable: response.status === void 0 || response.status >= 500,
|
|
4578
|
+
...response.authFailed ? { auth: true } : {},
|
|
4579
|
+
error: response.error
|
|
4580
|
+
};
|
|
4581
|
+
};
|
|
4582
|
+
}
|
|
4583
|
+
/** stderr progress, suppressed off a TTY so CI logs stay readable. */
|
|
4584
|
+
function progressWriter(prefix) {
|
|
4585
|
+
if (!process.stderr.isTTY) return void 0;
|
|
4586
|
+
return ({ done, total }) => {
|
|
4587
|
+
process.stderr.write(`\r${prefix}${done}/${total} `);
|
|
4588
|
+
};
|
|
4589
|
+
}
|
|
4590
|
+
/**
|
|
4591
|
+
* The command's core, exported for the unit tests. `seams` exists only so tests can
|
|
4592
|
+
* shrink the retry backoff — the CLI itself never passes it (PoC parity: 4 attempts,
|
|
4593
|
+
* 5 s linear).
|
|
4594
|
+
*/
|
|
4595
|
+
async function runEvalCommand(pathsOrUrls, options, seams = {}) {
|
|
4596
|
+
const override = parseOverride(options);
|
|
4597
|
+
if (!override.ok) {
|
|
4598
|
+
failJson({ message: override.message });
|
|
4599
|
+
return;
|
|
4600
|
+
}
|
|
4601
|
+
const expansion = expandSources(pathsOrUrls);
|
|
4602
|
+
if (!expansion.ok) {
|
|
4603
|
+
failJson({ message: expansion.message });
|
|
4604
|
+
return;
|
|
4605
|
+
}
|
|
4606
|
+
for (const duplicate of expansion.duplicates) process.stderr.write(`Warning: ${duplicate} was given more than once — ignoring the copy.\n`);
|
|
4607
|
+
const repeats = Math.max(1, Number.parseInt(options.repeats ?? "1", 10) || 1);
|
|
4608
|
+
const concurrency = Math.max(1, Number.parseInt(options.concurrency ?? String(CONCURRENCY_DEFAULT), 10) || CONCURRENCY_DEFAULT);
|
|
4609
|
+
const checked = /* @__PURE__ */ new Map();
|
|
4610
|
+
const files = [];
|
|
4611
|
+
for (const source of expansion.sources) {
|
|
4612
|
+
const result = await loadAndCheckEval(source, cliFetcher, { allowedSchemes: [
|
|
4613
|
+
"http:",
|
|
4614
|
+
"https:",
|
|
4615
|
+
"file:"
|
|
4616
|
+
] });
|
|
4617
|
+
if (!result.ok) {
|
|
4618
|
+
files.push({
|
|
4619
|
+
source,
|
|
4620
|
+
status: "invalid",
|
|
4621
|
+
errors: result.errors
|
|
4622
|
+
});
|
|
4623
|
+
continue;
|
|
4624
|
+
}
|
|
4625
|
+
checked.set(source, result);
|
|
4626
|
+
files.push({
|
|
4627
|
+
source,
|
|
4628
|
+
status: "ok"
|
|
4629
|
+
});
|
|
4630
|
+
}
|
|
4631
|
+
if (checked.size === 0) {
|
|
4632
|
+
failJson({
|
|
4633
|
+
message: files.length === 1 ? "The eval file is not usable." : "None of the eval files are usable.",
|
|
4634
|
+
files: files.map((file) => ({
|
|
4635
|
+
source: file.source,
|
|
4636
|
+
errors: file.errors ?? []
|
|
4637
|
+
})),
|
|
4638
|
+
errors: files.flatMap((file) => file.errors ?? [])
|
|
4639
|
+
});
|
|
4640
|
+
return;
|
|
4641
|
+
}
|
|
4642
|
+
{
|
|
4643
|
+
const totalCases = [...checked.values()].reduce((sum, file) => sum + file.caseCount, 0);
|
|
4644
|
+
process.stderr.write(`${totalCases} case(s) × ${repeats} repeat(s) = ${totalCases * repeats} grading call(s)\n`);
|
|
4645
|
+
}
|
|
4646
|
+
let fileIndex = 0;
|
|
4647
|
+
for (const file of files) {
|
|
4648
|
+
fileIndex += 1;
|
|
4649
|
+
const check = checked.get(file.source);
|
|
4650
|
+
if (!check) continue;
|
|
4651
|
+
const quizLlm = {
|
|
4652
|
+
provider: check.quizDump.llm.provider,
|
|
4653
|
+
model: check.quizDump.llm.model
|
|
4654
|
+
};
|
|
4655
|
+
const effective = override.llm ?? quizLlm;
|
|
4656
|
+
const llm = {
|
|
4657
|
+
...effective,
|
|
4658
|
+
...override.llm ? { overrides: quizLlm } : {}
|
|
4659
|
+
};
|
|
4660
|
+
const prefix = files.length > 1 ? `(${fileIndex}/${files.length}) ${check.evalFile.id}: ` : "";
|
|
4661
|
+
file.result = await runEval("quiz", check, {
|
|
4662
|
+
grade: makeGradeFn(options.server, effective),
|
|
4663
|
+
concurrency,
|
|
4664
|
+
repeats,
|
|
4665
|
+
llm,
|
|
4666
|
+
onProgress: progressWriter(prefix),
|
|
4667
|
+
...seams.retry ? { retry: seams.retry } : {}
|
|
4668
|
+
});
|
|
4669
|
+
if (process.stderr.isTTY) process.stderr.write("\n");
|
|
4670
|
+
}
|
|
4671
|
+
const batch = summarizeBatch(files);
|
|
4672
|
+
const payload = JSON.stringify(batch, null, 2);
|
|
4673
|
+
if (options.json) console.log(payload);
|
|
4674
|
+
else if (files.length === 1 && files[0]?.result) console.log(formatEvalReport(files[0].result, files[0].source));
|
|
4675
|
+
else console.log(formatEvalBatchReport(batch));
|
|
4676
|
+
if (options.out) try {
|
|
4677
|
+
await writeFile(options.out, `${payload}\n`, "utf8");
|
|
4678
|
+
} catch (error) {
|
|
4679
|
+
failJson({ message: `Could not write ${options.out}: ${error instanceof Error ? error.message : error}` });
|
|
4680
|
+
return;
|
|
4681
|
+
}
|
|
4682
|
+
if (options.report) try {
|
|
4683
|
+
await writeFile(options.report, renderEvalMarkdownReport(batch, {
|
|
4684
|
+
generatedAt: /* @__PURE__ */ new Date(),
|
|
4685
|
+
cliVersion: cliVersion(),
|
|
4686
|
+
repeats,
|
|
4687
|
+
concurrency
|
|
4688
|
+
}), "utf8");
|
|
4689
|
+
} catch (error) {
|
|
4690
|
+
failJson({ message: `Could not write ${options.report}: ${error instanceof Error ? error.message : error}` });
|
|
4691
|
+
return;
|
|
4692
|
+
}
|
|
4693
|
+
process.exitCode = batchPassed(batch) ? 0 : 1;
|
|
4694
|
+
}
|
|
4695
|
+
function registerEval(program) {
|
|
4696
|
+
program.command("eval").description("Grade a file of golden answers against its quiz's real rubric and report the result").argument("<evalPathOrUrl...>", "one or more eval YAML files (paths, http(s)/file URLs, or a quoted glob pattern)").option("--server <url>", "Novedu server base URL (defaults to the NOVEDU_SERVER env var, then production)").option("--concurrency <n>", "grading calls in flight per file", String(CONCURRENCY_DEFAULT)).option("--repeats <n>", "grade every answer N times and take the majority verdict", "1").option("--llm-provider <provider>", "grade with this provider instead of the quiz's (\"SCCH\" or \"Azure Foundry\"; needs --llm-model)").option("--llm-model <model>", "grade with this model instead of the quiz's (needs --llm-provider)").option("--json", "print the machine-readable batch report on stdout").option("--out <file>", "additionally write the machine-readable batch report to a file").option("--report <file>", "additionally write a readable Markdown report to a file").addHelpText("after", `
|
|
4697
|
+
Examples:
|
|
4698
|
+
# Evaluate one quiz's golden answers
|
|
4699
|
+
$ novedu-cli eval ./0010-welcome-quiz.eval.yaml
|
|
4700
|
+
|
|
4701
|
+
# A whole course part (quote the pattern so the CLI expands it, ** included)
|
|
4702
|
+
$ novedu-cli eval "./part-1/**/*.eval.yaml"
|
|
4703
|
+
|
|
4704
|
+
# Measure grader stability: 3 runs per answer, majority verdict
|
|
4705
|
+
$ novedu-cli eval ./my-quiz.eval.yaml --repeats 3
|
|
4706
|
+
|
|
4707
|
+
# How would this rubric perform on another model? (both flags, always together)
|
|
4708
|
+
$ novedu-cli eval ./my-quiz.eval.yaml --llm-provider "Azure Foundry" --llm-model gpt-5-mini
|
|
4709
|
+
|
|
4710
|
+
# Machine-readable, for CI
|
|
4711
|
+
$ novedu-cli eval ./my-quiz.eval.yaml --json --out eval-report.json
|
|
4712
|
+
|
|
4713
|
+
# A readable Markdown report (questions, golden answers, grader feedback, tokens)
|
|
4714
|
+
$ novedu-cli eval ./my-quiz.eval.yaml --report eval-report.md`).action(async (pathsOrUrls, options) => {
|
|
4715
|
+
await runEvalCommand(pathsOrUrls, options);
|
|
4716
|
+
});
|
|
4717
|
+
}
|
|
4718
|
+
//#endregion
|
|
4719
|
+
//#region src/commands/files.ts
|
|
4720
|
+
const SERVER_OPTION$2 = ["--server <url>", "Novedu server base URL (defaults to the NOVEDU_SERVER env var, then production)"];
|
|
4721
|
+
async function readStdin() {
|
|
4722
|
+
const chunks = [];
|
|
4723
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
4724
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
4725
|
+
}
|
|
4726
|
+
function registerFiles(program) {
|
|
4727
|
+
const files = program.command("files").description("Manage app-hosted YAML files on the Novedu server");
|
|
4728
|
+
files.command("upload <name>").description("Create or update an app-hosted YAML file from --file or stdin (validated server-side)").option("--kind <kind>", "file kind (tutor, fragment, quiz, writing, coding) — required when creating").option("--file <path>", "read the YAML from this path instead of stdin").option(...SERVER_OPTION$2).action(async (name, options) => {
|
|
4729
|
+
let content;
|
|
4730
|
+
try {
|
|
4731
|
+
content = options.file === void 0 ? await readStdin() : await readFile(options.file, "utf8");
|
|
4732
|
+
} catch (error) {
|
|
4733
|
+
failJson({ message: `Could not read ${options.file}: ${error instanceof Error ? error.message : error}` });
|
|
4734
|
+
return;
|
|
4735
|
+
}
|
|
4736
|
+
await runApiRequest({
|
|
4737
|
+
server: options.server,
|
|
4738
|
+
path: `/api/files/${encodeURIComponent(name)}`,
|
|
4739
|
+
method: "PUT",
|
|
4740
|
+
body: {
|
|
4741
|
+
...options.kind === void 0 ? {} : { kind: options.kind },
|
|
4742
|
+
content
|
|
4743
|
+
}
|
|
4744
|
+
});
|
|
4745
|
+
});
|
|
4746
|
+
files.command("list").description("List app-hosted YAML files (defaults to only your own, like the web list)").option("--search <q>", "contains-filter over name/title/description").option("--all", "include files last written by other teachers").option(...SERVER_OPTION$2).action(async (options) => {
|
|
4747
|
+
const params = new URLSearchParams();
|
|
4748
|
+
if (options.search) params.set("q", options.search);
|
|
4749
|
+
if (options.all) params.set("mine", "0");
|
|
4750
|
+
const query = params.toString();
|
|
4751
|
+
await runApiRequest({
|
|
4752
|
+
server: options.server,
|
|
4753
|
+
path: `/api/files${query ? `?${query}` : ""}`
|
|
4754
|
+
});
|
|
4755
|
+
});
|
|
4756
|
+
}
|
|
4757
|
+
//#endregion
|
|
4758
|
+
//#region ../lib/file-name.ts
|
|
4759
|
+
/**
|
|
4760
|
+
* Maps a filename or bare extension (with or without a leading dot, any case)
|
|
4761
|
+
* to an {@link ImageMime}; returns `null` for anything unrecognized. `jpg`/`jpeg`
|
|
4762
|
+
* both map to `image/jpeg`, `svg` to `image/svg+xml`.
|
|
4763
|
+
*/
|
|
4764
|
+
function imageMimeFromExtension(filename) {
|
|
4765
|
+
const lastDot = filename.lastIndexOf(".");
|
|
4766
|
+
switch ((lastDot >= 0 ? filename.slice(lastDot + 1) : filename).toLowerCase()) {
|
|
4767
|
+
case "png": return "image/png";
|
|
4768
|
+
case "jpg":
|
|
4769
|
+
case "jpeg": return "image/jpeg";
|
|
4770
|
+
case "svg": return "image/svg+xml";
|
|
4771
|
+
default: return null;
|
|
4772
|
+
}
|
|
4773
|
+
}
|
|
4774
|
+
//#endregion
|
|
4775
|
+
//#region src/commands/images.ts
|
|
4776
|
+
const SERVER_OPTION$1 = ["--server <url>", "Novedu server base URL (defaults to the NOVEDU_SERVER env var, then production)"];
|
|
4777
|
+
function registerImages(program) {
|
|
4778
|
+
const images = program.command("images").description("Manage app-hosted images on the Novedu server");
|
|
4779
|
+
images.command("upload <name>").description("Upload a NEW image (.png, .jpg/.jpeg or .svg, max 5 MB) from --file").option("--file <path>", "the image file to upload (required — images are binary, no stdin)").option("--credit <text>", "optional attribution shown with the image (max 512 chars)").option(...SERVER_OPTION$1).action(async (name, options) => {
|
|
4780
|
+
if (options.file === void 0) {
|
|
4781
|
+
failJson({ message: "Pass --file <path> — images are binary, stdin is not supported." });
|
|
4782
|
+
return;
|
|
4783
|
+
}
|
|
4784
|
+
const mime = imageMimeFromExtension(options.file);
|
|
4785
|
+
if (mime === null) {
|
|
4786
|
+
failJson({ message: "Only .png, .jpg/.jpeg and .svg files can be uploaded." });
|
|
4787
|
+
return;
|
|
4788
|
+
}
|
|
4789
|
+
let bytes;
|
|
4790
|
+
try {
|
|
4791
|
+
bytes = await readFile(options.file);
|
|
4792
|
+
} catch (error) {
|
|
4793
|
+
failJson({ message: `Could not read ${options.file}: ${error instanceof Error ? error.message : error}` });
|
|
4794
|
+
return;
|
|
4795
|
+
}
|
|
4796
|
+
const slot = await performApiRequest({
|
|
4797
|
+
server: options.server,
|
|
4798
|
+
path: `/api/images/${encodeURIComponent(name)}`,
|
|
4799
|
+
method: "POST",
|
|
4800
|
+
body: {
|
|
4801
|
+
mime,
|
|
4802
|
+
byteSize: bytes.length
|
|
4803
|
+
}
|
|
4804
|
+
});
|
|
4805
|
+
if (!slot.ok) return;
|
|
4806
|
+
const { uploadUrl, blobPath } = slot.payload ?? {};
|
|
4807
|
+
if (typeof uploadUrl !== "string" || typeof blobPath !== "string") {
|
|
4808
|
+
failJson({ message: "Unexpected response from the server." });
|
|
4809
|
+
return;
|
|
4810
|
+
}
|
|
4811
|
+
let putResponse;
|
|
4812
|
+
try {
|
|
4813
|
+
putResponse = await fetch(uploadUrl, {
|
|
4814
|
+
method: "PUT",
|
|
4815
|
+
headers: {
|
|
4816
|
+
"x-ms-blob-type": "BlockBlob",
|
|
4817
|
+
"content-type": mime
|
|
4818
|
+
},
|
|
4819
|
+
body: new Uint8Array(bytes)
|
|
4820
|
+
});
|
|
4821
|
+
} catch (error) {
|
|
4822
|
+
failJson({ message: `Could not reach storage: ${error instanceof Error ? error.message : error}` });
|
|
4823
|
+
return;
|
|
4824
|
+
}
|
|
4825
|
+
if (!putResponse.ok) {
|
|
4826
|
+
failJson({ message: `The upload to storage failed: HTTP ${putResponse.status}. Try again.` });
|
|
4827
|
+
return;
|
|
4828
|
+
}
|
|
4829
|
+
await runApiRequest({
|
|
4830
|
+
server: options.server,
|
|
4831
|
+
path: `/api/images/${encodeURIComponent(name)}/confirm`,
|
|
4832
|
+
method: "POST",
|
|
4833
|
+
body: {
|
|
4834
|
+
blobPath,
|
|
4835
|
+
mime,
|
|
4836
|
+
...options.credit === void 0 ? {} : { credit: options.credit }
|
|
4837
|
+
}
|
|
4838
|
+
});
|
|
4839
|
+
});
|
|
4840
|
+
images.command("list").description("List app-hosted images (defaults to only your own, like the web list)").option("--search <q>", "contains-filter over the name").option("--all", "include images uploaded by other teachers").option(...SERVER_OPTION$1).action(async (options) => {
|
|
4841
|
+
const params = new URLSearchParams();
|
|
4842
|
+
if (options.search) params.set("q", options.search);
|
|
4843
|
+
if (options.all) params.set("mine", "0");
|
|
4844
|
+
const query = params.toString();
|
|
4845
|
+
await runApiRequest({
|
|
4846
|
+
server: options.server,
|
|
4847
|
+
path: `/api/images${query ? `?${query}` : ""}`
|
|
4848
|
+
});
|
|
4849
|
+
});
|
|
4850
|
+
}
|
|
4851
|
+
//#endregion
|
|
4852
|
+
//#region src/commands/login.ts
|
|
4853
|
+
function registerLogin(program) {
|
|
4854
|
+
program.command("login").description("Sign in to Microsoft Entra ID (opens your browser)").option("--device-code", "sign in with the device code flow instead (for machines without a browser; the tenant must allow it)").addHelpText("after", `
|
|
4855
|
+
Sign-in is the one human-assisted step: by default a browser window opens for
|
|
4856
|
+
the Microsoft sign-in (first-time users see a one-time consent prompt). On a
|
|
4857
|
+
machine without a browser, --device-code prints a verification URL and a code
|
|
4858
|
+
to enter from any other device — note that some tenants block the device code
|
|
4859
|
+
flow by policy (error 53003). Every other command then works non-interactively
|
|
4860
|
+
from the cached credentials. Already signed in? The command says so and exits
|
|
4861
|
+
— it never blocks.`).action(async (options) => {
|
|
4862
|
+
const pca = buildPca();
|
|
4863
|
+
const cached = await acquireSilent(pca);
|
|
4864
|
+
if (cached) {
|
|
4865
|
+
console.log(`Already signed in as ${displayName(cached)}.`);
|
|
4866
|
+
return;
|
|
4867
|
+
}
|
|
4868
|
+
const result = options.deviceCode ? await acquireByDeviceCode(pca, (message) => console.log(message)) : await acquireInteractive(pca, (url) => {
|
|
4869
|
+
console.log("A browser window should open for the Microsoft sign-in.");
|
|
4870
|
+
console.log(`If it does not, open this URL yourself:\n${url}`);
|
|
4871
|
+
});
|
|
4872
|
+
console.log(`Signed in as ${displayName(result)}.`);
|
|
4873
|
+
});
|
|
4874
|
+
}
|
|
4875
|
+
//#endregion
|
|
4876
|
+
//#region src/commands/logout.ts
|
|
4877
|
+
function registerLogout(program) {
|
|
4878
|
+
program.command("logout").description("Sign out: remove the cached credentials from this machine").addHelpText("after", `
|
|
4879
|
+
Purely local — already-issued access tokens stay valid until they expire
|
|
4880
|
+
(about an hour). Running it while signed out is fine.`).action(async () => {
|
|
4881
|
+
const cache = buildPca().getTokenCache();
|
|
4882
|
+
for (const account of await cache.getAllAccounts()) await cache.removeAccount(account);
|
|
4883
|
+
rmSync(TOKEN_CACHE_PATH, { force: true });
|
|
4884
|
+
console.log("Signed out.");
|
|
4885
|
+
});
|
|
3784
4886
|
}
|
|
3785
4887
|
//#endregion
|
|
3786
4888
|
//#region src/commands/prompts.ts
|
|
@@ -3901,11 +5003,11 @@ function registerWhoami(program) {
|
|
|
3901
5003
|
}
|
|
3902
5004
|
//#endregion
|
|
3903
5005
|
//#region src/main.ts
|
|
3904
|
-
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
3905
5006
|
const program = new Command();
|
|
3906
|
-
program.name("novedu-cli").description("Command-line companion for the Novedu chat app").version(
|
|
5007
|
+
program.name("novedu-cli").description("Command-line companion for the Novedu chat app").version(cliVersion());
|
|
3907
5008
|
registerValidate(program);
|
|
3908
5009
|
registerPrompts(program);
|
|
5010
|
+
registerEval(program);
|
|
3909
5011
|
registerLogin(program);
|
|
3910
5012
|
registerLogout(program);
|
|
3911
5013
|
registerWhoami(program);
|