@okhay-p/mivra 0.1.4 → 0.1.6
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 +2 -0
- package/THIRD_PARTY_NOTICES.md +250 -0
- package/dist/chunk-B47HA6IQ.js +2294 -0
- package/dist/chunk-B47HA6IQ.js.map +7 -0
- package/dist/{chunk-ODFBAPPH.js → chunk-DYXNHODU.js} +9 -3
- package/dist/chunk-DYXNHODU.js.map +7 -0
- package/dist/{chunk-KUKQU7EQ.js → chunk-VHOVRHI3.js} +38 -10
- package/dist/{chunk-KUKQU7EQ.js.map → chunk-VHOVRHI3.js.map} +2 -2
- package/dist/cli.js +807 -44
- package/dist/cli.js.map +4 -4
- package/dist/{client-5YDLS4KV.js → client-4UG5W5NJ.js} +2 -2
- package/dist/exercise-child.js +37 -0
- package/dist/exercise-child.js.map +7 -0
- package/dist/extract-child.js +1 -1
- package/dist/python-child.js +51 -0
- package/dist/python-child.js.map +7 -0
- package/dist/{start-76LKE3DL.js → start-SX3BCBIN.js} +1215 -237
- package/dist/start-SX3BCBIN.js.map +7 -0
- package/drizzle/0019_public_doctor_faustus.sql +1 -0
- package/drizzle/0020_early_wolfpack.sql +3 -0
- package/drizzle/meta/0019_snapshot.json +2288 -0
- package/drizzle/meta/0020_snapshot.json +2297 -0
- package/drizzle/meta/_journal.json +14 -0
- package/package.json +6 -1
- package/web/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
- package/web/assets/emscripten-module.browser-D72eEgXo.js +1 -0
- package/web/assets/exercise-workers/exercise.worker-DzC1lTCg.js +265 -0
- package/web/assets/exercise-workers/python-exercise.worker-CtSr-syJ.js +236 -0
- package/web/assets/ffi-4V2b7xu3.js +1 -0
- package/web/assets/index-D3M-SX0V.js +538 -0
- package/web/assets/index-DUFQVtIh.css +1 -0
- package/web/assets/module-ES6BEMUI-Chb6aYUZ.js +1 -0
- package/web/assets/notes-graph.worker-Dqb5HK34.js +1 -0
- package/web/assets/render.worker-D6KYAHiU.js +537 -0
- package/web/index.html +8 -3
- package/dist/chunk-ODFBAPPH.js.map +0 -7
- package/dist/chunk-YACRW47X.js +0 -1203
- package/dist/chunk-YACRW47X.js.map +0 -7
- package/dist/start-76LKE3DL.js.map +0 -7
- package/web/assets/index-C_DsRKCc.css +0 -1
- package/web/assets/index-DbKDW1xS.js +0 -413
- package/web/assets/notes-graph.worker-DaVQvftJ.js +0 -1
- package/web/assets/render.worker-BAfybD27.js +0 -416
- /package/dist/{client-5YDLS4KV.js.map → client-4UG5W5NJ.js.map} +0 -0
|
@@ -0,0 +1,2294 @@
|
|
|
1
|
+
// ../protocol/src/code-exercise.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var EXERCISE_LANGUAGES = ["javascript", "python"];
|
|
4
|
+
var ExerciseLanguage = z.enum(EXERCISE_LANGUAGES);
|
|
5
|
+
var MAX_EXERCISE_CASES = 20;
|
|
6
|
+
var MAX_EXERCISE_CODE_CHARS = 1e4;
|
|
7
|
+
var MAX_SUBMITTED_CODE_CHARS = 5e4;
|
|
8
|
+
var MAX_CASE_INPUT_CHARS = 1e4;
|
|
9
|
+
var MAX_CASE_OUTPUT_CHARS = 2e4;
|
|
10
|
+
var MAX_CASE_ERROR_CHARS = 2e3;
|
|
11
|
+
var EXERCISE_LIMITS = {
|
|
12
|
+
timeMs: 2e3,
|
|
13
|
+
memoryBytes: 64 * 1024 * 1024,
|
|
14
|
+
stackBytes: 384 * 1024,
|
|
15
|
+
outputChars: MAX_CASE_OUTPUT_CHARS
|
|
16
|
+
};
|
|
17
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
18
|
+
var PYTHON_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
19
|
+
var PYTHON_KEYWORDS = new Set(
|
|
20
|
+
"False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" ")
|
|
21
|
+
);
|
|
22
|
+
var hidden = z.boolean().optional().describe("Hidden from the learner's view until they submit: use for edge cases. At least one case must be visible.");
|
|
23
|
+
var ExerciseStdioCaseInput = z.object({
|
|
24
|
+
kind: z.literal("stdio"),
|
|
25
|
+
stdin: z.string().max(MAX_CASE_INPUT_CHARS).describe('The text the program reads: in JavaScript the global `stdin` string or `readLine()`, in Python input() or sys.stdin. Use "" for none.'),
|
|
26
|
+
hidden
|
|
27
|
+
}).strict();
|
|
28
|
+
var ExerciseCallCaseInput = z.object({
|
|
29
|
+
kind: z.literal("call"),
|
|
30
|
+
args: z.string().max(MAX_CASE_INPUT_CHARS).describe('The arguments to call functionName with, as a JSON array, e.g. "[[3, 1, 2], 2]" or "[]".'),
|
|
31
|
+
hidden
|
|
32
|
+
}).strict();
|
|
33
|
+
var ExerciseCaseInput = z.discriminatedUnion("kind", [ExerciseStdioCaseInput, ExerciseCallCaseInput]);
|
|
34
|
+
var ExerciseExpected = z.union([
|
|
35
|
+
z.object({ stdout: z.string().max(MAX_CASE_OUTPUT_CHARS) }).strict(),
|
|
36
|
+
z.object({ returned: z.string().max(MAX_CASE_OUTPUT_CHARS) }).strict()
|
|
37
|
+
]);
|
|
38
|
+
var exerciseFields = {
|
|
39
|
+
concept: z.string().trim().min(1).max(80).describe('Short label for the concept being practised, e.g. "array reduce". Used to track progress.'),
|
|
40
|
+
title: z.string().trim().min(1).max(120),
|
|
41
|
+
instructions: z.string().trim().min(1).max(4e3).describe("What the learner's code must do, as markdown. Say exactly what to print or return, and for stdio how the input is laid out."),
|
|
42
|
+
language: ExerciseLanguage,
|
|
43
|
+
starterCode: z.string().max(MAX_EXERCISE_CODE_CHARS).describe("The code the editor starts with, e.g. the function's signature with an empty body. May be empty."),
|
|
44
|
+
functionName: z.string().regex(IDENTIFIER).max(80).optional().describe("The function call cases call, declared at the top level of the learner's code. Required when there are call cases.")
|
|
45
|
+
};
|
|
46
|
+
function checkCases(spec, ctx) {
|
|
47
|
+
if (spec.language === "python" && spec.functionName !== void 0 && (!PYTHON_IDENTIFIER.test(spec.functionName) || PYTHON_KEYWORDS.has(spec.functionName))) {
|
|
48
|
+
ctx.addIssue({ code: "custom", path: ["functionName"], message: "functionName must be a Python identifier" });
|
|
49
|
+
}
|
|
50
|
+
if (spec.cases.every((c) => c.hidden)) ctx.addIssue({ code: "custom", path: ["cases"], message: "at least one case must be visible" });
|
|
51
|
+
const calls = spec.cases.some((c) => c.kind === "call");
|
|
52
|
+
if (calls && !spec.functionName) ctx.addIssue({ code: "custom", path: ["functionName"], message: "functionName is required for call cases" });
|
|
53
|
+
spec.cases.forEach((c, i) => {
|
|
54
|
+
if (c.kind !== "call") return;
|
|
55
|
+
let args;
|
|
56
|
+
try {
|
|
57
|
+
args = JSON.parse(c.args);
|
|
58
|
+
} catch {
|
|
59
|
+
return ctx.addIssue({ code: "custom", path: ["cases", i, "args"], message: "args must be a JSON array" });
|
|
60
|
+
}
|
|
61
|
+
if (!Array.isArray(args)) ctx.addIssue({ code: "custom", path: ["cases", i, "args"], message: "args must be a JSON array" });
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
var CodeExerciseInput = z.object({
|
|
65
|
+
...exerciseFields,
|
|
66
|
+
cases: z.array(ExerciseCaseInput).min(1).max(MAX_EXERCISE_CASES).describe("1-20 test cases. Keep each fast: every case has a 2 s limit."),
|
|
67
|
+
referenceSolution: z.string().min(1).max(MAX_EXERCISE_CODE_CHARS).describe("A complete correct solution. Mivra runs it on every case to get the expected results; it is never shown to the learner. It must be deterministic (no random numbers or clock time).")
|
|
68
|
+
}).strict().superRefine(checkCases);
|
|
69
|
+
var ExerciseCase = z.discriminatedUnion("kind", [
|
|
70
|
+
ExerciseStdioCaseInput.extend({ expected: ExerciseExpected }),
|
|
71
|
+
ExerciseCallCaseInput.extend({ expected: ExerciseExpected })
|
|
72
|
+
]);
|
|
73
|
+
var CodeExerciseSpec = z.object({
|
|
74
|
+
...exerciseFields,
|
|
75
|
+
cases: z.array(ExerciseCase).min(1).max(MAX_EXERCISE_CASES),
|
|
76
|
+
referenceSolution: z.string().max(MAX_EXERCISE_CODE_CHARS)
|
|
77
|
+
}).strict();
|
|
78
|
+
var ExercisePublicCase = z.discriminatedUnion("kind", [
|
|
79
|
+
z.object({ kind: z.literal("stdio"), stdin: z.string(), hidden: z.boolean(), expected: ExerciseExpected.optional() }).strict(),
|
|
80
|
+
z.object({ kind: z.literal("call"), args: z.string(), hidden: z.boolean(), expected: ExerciseExpected.optional() }).strict()
|
|
81
|
+
]);
|
|
82
|
+
var CodeExercisePublic = z.object({
|
|
83
|
+
concept: z.string(),
|
|
84
|
+
title: z.string(),
|
|
85
|
+
instructions: z.string(),
|
|
86
|
+
language: ExerciseLanguage,
|
|
87
|
+
starterCode: z.string(),
|
|
88
|
+
functionName: z.string().optional(),
|
|
89
|
+
cases: z.array(ExercisePublicCase)
|
|
90
|
+
}).strict();
|
|
91
|
+
function toCodeExercisePublic(spec) {
|
|
92
|
+
return {
|
|
93
|
+
concept: spec.concept,
|
|
94
|
+
title: spec.title,
|
|
95
|
+
instructions: spec.instructions,
|
|
96
|
+
language: spec.language,
|
|
97
|
+
starterCode: spec.starterCode,
|
|
98
|
+
...spec.functionName ? { functionName: spec.functionName } : {},
|
|
99
|
+
cases: spec.cases.map((c) => {
|
|
100
|
+
const isHidden = c.hidden ?? false;
|
|
101
|
+
const input = c.kind === "stdio" ? { kind: "stdio", stdin: c.stdin } : { kind: "call", args: c.args };
|
|
102
|
+
return { ...input, hidden: isHidden, ...isHidden ? {} : { expected: c.expected } };
|
|
103
|
+
})
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
var ExerciseCaseRun = z.object({
|
|
107
|
+
stdout: z.string().max(MAX_CASE_OUTPUT_CHARS),
|
|
108
|
+
stderr: z.string().max(MAX_CASE_OUTPUT_CHARS).optional(),
|
|
109
|
+
returned: z.string().max(MAX_CASE_OUTPUT_CHARS).optional(),
|
|
110
|
+
error: z.string().max(MAX_CASE_ERROR_CHARS).optional()
|
|
111
|
+
}).strict();
|
|
112
|
+
var CodeExerciseAnswer = z.object({
|
|
113
|
+
code: z.string().max(MAX_SUBMITTED_CODE_CHARS),
|
|
114
|
+
results: z.array(ExerciseCaseRun).min(1).max(MAX_EXERCISE_CASES)
|
|
115
|
+
}).strict();
|
|
116
|
+
var CodeExerciseGrade = z.object({
|
|
117
|
+
correct: z.boolean(),
|
|
118
|
+
passed: z.number().int().nonnegative(),
|
|
119
|
+
total: z.number().int().positive(),
|
|
120
|
+
cases: z.array(z.object({ passed: z.boolean() }).strict())
|
|
121
|
+
}).strict();
|
|
122
|
+
function normaliseOutput(text) {
|
|
123
|
+
return text.replace(/\r\n?/g, "\n").split("\n").map((line) => line.replace(/[ \t]+$/, "")).join("\n").replace(/\n+$/, "");
|
|
124
|
+
}
|
|
125
|
+
function canonical(value) {
|
|
126
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
127
|
+
if (value && typeof value === "object") {
|
|
128
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
|
|
129
|
+
}
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
function sameReturnValue(a, b) {
|
|
133
|
+
if (a === "undefined" || b === "undefined") return a === b;
|
|
134
|
+
try {
|
|
135
|
+
return JSON.stringify(canonical(JSON.parse(a))) === JSON.stringify(canonical(JSON.parse(b)));
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function casePassed(expected, run) {
|
|
141
|
+
if (run.error !== void 0) return false;
|
|
142
|
+
if ("stdout" in expected) return normaliseOutput(run.stdout) === normaliseOutput(expected.stdout);
|
|
143
|
+
return run.returned !== void 0 && sameReturnValue(run.returned, expected.returned);
|
|
144
|
+
}
|
|
145
|
+
function expectedFrom(testCase, run) {
|
|
146
|
+
if (run.error !== void 0) throw new Error(run.error);
|
|
147
|
+
if (testCase.kind === "stdio") return { stdout: normaliseOutput(run.stdout) };
|
|
148
|
+
if (run.returned === void 0) throw new Error("The function returned nothing Mivra could record");
|
|
149
|
+
return { returned: run.returned };
|
|
150
|
+
}
|
|
151
|
+
function gradeCodeExercise(spec, answer) {
|
|
152
|
+
if (answer.results.length !== spec.cases.length) {
|
|
153
|
+
throw new RangeError(`Expected results for ${spec.cases.length} cases, got ${answer.results.length}`);
|
|
154
|
+
}
|
|
155
|
+
const cases = spec.cases.map((c, i) => ({ passed: casePassed(c.expected, answer.results[i]) }));
|
|
156
|
+
const passed = cases.filter((c) => c.passed).length;
|
|
157
|
+
return { correct: passed === cases.length, passed, total: cases.length, cases };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ../protocol/src/code-exercise-runner.ts
|
|
161
|
+
var FILENAME = "solution.js";
|
|
162
|
+
var PRELUDE = `(() => {
|
|
163
|
+
const write = globalThis.__mivra_write;
|
|
164
|
+
const text = globalThis.__mivra_stdin;
|
|
165
|
+
delete globalThis.__mivra_write;
|
|
166
|
+
delete globalThis.__mivra_stdin;
|
|
167
|
+
const show = (value) => {
|
|
168
|
+
if (typeof value === "string") return value;
|
|
169
|
+
if (typeof value === "function") return "[Function " + (value.name || "anonymous") + "]";
|
|
170
|
+
if (typeof value === "object" && value !== null) {
|
|
171
|
+
if (value instanceof Error) return String(value);
|
|
172
|
+
try { const json = JSON.stringify(value); if (json !== undefined) return json; } catch {}
|
|
173
|
+
}
|
|
174
|
+
return String(value);
|
|
175
|
+
};
|
|
176
|
+
const line = (args) => Array.prototype.map.call(args, show).join(" ");
|
|
177
|
+
const out = function () { write(0, line(arguments)); };
|
|
178
|
+
const err = function () { write(1, line(arguments)); };
|
|
179
|
+
globalThis.console = { log: out, info: out, debug: out, warn: err, error: err };
|
|
180
|
+
const lines = text === "" ? [] : text.replace(/\\r\\n?/g, "\\n").replace(/\\n$/, "").split("\\n");
|
|
181
|
+
let next = 0;
|
|
182
|
+
globalThis.stdin = text;
|
|
183
|
+
globalThis.readLine = () => (next < lines.length ? lines[next++] : null);
|
|
184
|
+
})();`;
|
|
185
|
+
var SERIALISE = `(value) => {
|
|
186
|
+
if (value === undefined) return "undefined";
|
|
187
|
+
const json = JSON.stringify(value);
|
|
188
|
+
return json === undefined ? "undefined" : json;
|
|
189
|
+
}`;
|
|
190
|
+
var Capped = class {
|
|
191
|
+
constructor(limit) {
|
|
192
|
+
this.limit = limit;
|
|
193
|
+
}
|
|
194
|
+
limit;
|
|
195
|
+
stdout = "";
|
|
196
|
+
stderr = "";
|
|
197
|
+
exceeded = false;
|
|
198
|
+
write(stream, text) {
|
|
199
|
+
if (this.exceeded) return;
|
|
200
|
+
const line = `${text}
|
|
201
|
+
`;
|
|
202
|
+
const room = this.limit - this.stdout.length - this.stderr.length;
|
|
203
|
+
if (line.length > room) this.exceeded = true;
|
|
204
|
+
const kept = line.slice(0, Math.max(0, room));
|
|
205
|
+
if (stream === 0) this.stdout += kept;
|
|
206
|
+
else this.stderr += kept;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
var OUTPUT_EXCEEDED = (chars) => `Output limit exceeded (${chars.toLocaleString("en-US")} characters).`;
|
|
210
|
+
var STACK_EXCEEDED = "Stack limit exceeded: the code recursed too deeply.";
|
|
211
|
+
var formatBytes = (bytes) => `${Math.round(bytes / (1024 * 1024))} MB`;
|
|
212
|
+
function runExerciseCase(module, { code, functionName, testCase, limits = EXERCISE_LIMITS, now = Date.now }) {
|
|
213
|
+
const output = new Capped(limits.outputChars);
|
|
214
|
+
const deadline = now() + limits.timeMs;
|
|
215
|
+
let timedOut = false;
|
|
216
|
+
const runtime = module.newRuntime();
|
|
217
|
+
runtime.setMaxStackSize(limits.stackBytes);
|
|
218
|
+
runtime.setInterruptHandler(() => {
|
|
219
|
+
if (now() > deadline) timedOut = true;
|
|
220
|
+
return timedOut || output.exceeded;
|
|
221
|
+
});
|
|
222
|
+
const describe = (vm2, handle) => {
|
|
223
|
+
if (timedOut) return `Time limit exceeded (${limits.timeMs / 1e3} s): the code ran too long, or never stopped.`;
|
|
224
|
+
if (output.exceeded) return OUTPUT_EXCEEDED(limits.outputChars);
|
|
225
|
+
let message = "The code threw an error.";
|
|
226
|
+
try {
|
|
227
|
+
const dumped = vm2.dump(handle);
|
|
228
|
+
if (dumped && typeof dumped === "object" && "message" in dumped) {
|
|
229
|
+
const { name, message: text, stack } = dumped;
|
|
230
|
+
message = `${typeof name === "string" ? name : "Error"}: ${String(text)}`;
|
|
231
|
+
const line = typeof stack === "string" ? new RegExp(`${FILENAME.replace(".", "\\.")}:(\\d+)`).exec(stack)?.[1] : void 0;
|
|
232
|
+
if (line) message += ` (line ${line})`;
|
|
233
|
+
} else {
|
|
234
|
+
message = `Uncaught ${typeof dumped === "string" ? dumped : JSON.stringify(dumped) ?? String(dumped)}`;
|
|
235
|
+
}
|
|
236
|
+
} catch {
|
|
237
|
+
}
|
|
238
|
+
return friendly(message);
|
|
239
|
+
};
|
|
240
|
+
const friendly = (message) => {
|
|
241
|
+
if (/out of memory/i.test(message)) return `Memory limit exceeded (${formatBytes(limits.memoryBytes)}).`;
|
|
242
|
+
if (/stack overflow|call stack size/i.test(message)) return STACK_EXCEEDED;
|
|
243
|
+
return message;
|
|
244
|
+
};
|
|
245
|
+
const finish = (outcome) => {
|
|
246
|
+
const result = output.exceeded && outcome.error === void 0 ? { error: OUTPUT_EXCEEDED(limits.outputChars) } : outcome;
|
|
247
|
+
return {
|
|
248
|
+
stdout: output.stdout,
|
|
249
|
+
...output.stderr ? { stderr: output.stderr } : {},
|
|
250
|
+
...result.returned !== void 0 ? { returned: result.returned } : {},
|
|
251
|
+
...result.error !== void 0 ? { error: result.error.slice(0, MAX_CASE_ERROR_CHARS) } : {}
|
|
252
|
+
};
|
|
253
|
+
};
|
|
254
|
+
let vm;
|
|
255
|
+
try {
|
|
256
|
+
vm = runtime.newContext();
|
|
257
|
+
const context = vm;
|
|
258
|
+
const write = context.newFunction("__mivra_write", (stream, text) => {
|
|
259
|
+
output.write(context.getNumber(stream), context.getString(text));
|
|
260
|
+
});
|
|
261
|
+
context.setProp(context.global, "__mivra_write", write);
|
|
262
|
+
write.dispose();
|
|
263
|
+
const stdin = context.newString(testCase.kind === "stdio" ? testCase.stdin : "");
|
|
264
|
+
context.setProp(context.global, "__mivra_stdin", stdin);
|
|
265
|
+
stdin.dispose();
|
|
266
|
+
const evaluate = (source, filename) => {
|
|
267
|
+
const result = context.evalCode(source, filename);
|
|
268
|
+
if (result.error) {
|
|
269
|
+
const error = describe(context, result.error);
|
|
270
|
+
result.error.dispose();
|
|
271
|
+
return { error };
|
|
272
|
+
}
|
|
273
|
+
return { value: result.value };
|
|
274
|
+
};
|
|
275
|
+
const settle = (handle) => {
|
|
276
|
+
for (; ; ) {
|
|
277
|
+
const jobs = runtime.executePendingJobs();
|
|
278
|
+
if (jobs.error) {
|
|
279
|
+
const error = describe(context, jobs.error);
|
|
280
|
+
jobs.error.dispose();
|
|
281
|
+
handle.dispose();
|
|
282
|
+
return { error };
|
|
283
|
+
}
|
|
284
|
+
const state = context.getPromiseState(handle);
|
|
285
|
+
if (state.type === "fulfilled") {
|
|
286
|
+
if (state.notAPromise) return { value: handle };
|
|
287
|
+
handle.dispose();
|
|
288
|
+
return { value: state.value };
|
|
289
|
+
}
|
|
290
|
+
if (state.type === "rejected") {
|
|
291
|
+
const error = describe(context, state.error);
|
|
292
|
+
state.error.dispose();
|
|
293
|
+
handle.dispose();
|
|
294
|
+
return { error };
|
|
295
|
+
}
|
|
296
|
+
if (jobs.value === 0) {
|
|
297
|
+
handle.dispose();
|
|
298
|
+
return { error: timedOut ? describe(context, context.undefined) : "The returned promise never settled." };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const prelude = context.evalCode(PRELUDE, "prelude.js");
|
|
303
|
+
if (prelude.error) {
|
|
304
|
+
const error = describe(context, prelude.error);
|
|
305
|
+
prelude.error.dispose();
|
|
306
|
+
return finish({ error });
|
|
307
|
+
}
|
|
308
|
+
prelude.value.dispose();
|
|
309
|
+
const ran = evaluate(code, FILENAME);
|
|
310
|
+
if ("error" in ran) return finish(ran);
|
|
311
|
+
const program = settle(ran.value);
|
|
312
|
+
if ("error" in program) return finish(program);
|
|
313
|
+
program.value.dispose();
|
|
314
|
+
if (testCase.kind === "stdio") return finish({});
|
|
315
|
+
const name = functionName ?? "";
|
|
316
|
+
const call = evaluate(
|
|
317
|
+
`typeof ${name} === "function" ? ${name}(...JSON.parse(${JSON.stringify(testCase.args)})) : (() => { throw new TypeError(${JSON.stringify(`${name} is not defined as a function`)}); })()`,
|
|
318
|
+
"call.js"
|
|
319
|
+
);
|
|
320
|
+
if ("error" in call) return finish(call);
|
|
321
|
+
const value = settle(call.value);
|
|
322
|
+
if ("error" in value) return finish(value);
|
|
323
|
+
const serialise = evaluate(SERIALISE, "serialise.js");
|
|
324
|
+
if ("error" in serialise) {
|
|
325
|
+
value.value.dispose();
|
|
326
|
+
return finish(serialise);
|
|
327
|
+
}
|
|
328
|
+
const json = context.callFunction(serialise.value, context.undefined, value.value);
|
|
329
|
+
serialise.value.dispose();
|
|
330
|
+
value.value.dispose();
|
|
331
|
+
if (json.error) {
|
|
332
|
+
const error = `The return value can't be recorded as JSON: ${describe(context, json.error)}`;
|
|
333
|
+
json.error.dispose();
|
|
334
|
+
return finish({ error });
|
|
335
|
+
}
|
|
336
|
+
const returned = context.getString(json.value);
|
|
337
|
+
json.value.dispose();
|
|
338
|
+
if (returned.length > limits.outputChars) return finish({ error: `The return value is too large (over ${limits.outputChars.toLocaleString("en-US")} characters).` });
|
|
339
|
+
return finish({ returned });
|
|
340
|
+
} catch (error) {
|
|
341
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
342
|
+
const known = friendly(message);
|
|
343
|
+
return finish({ error: known !== message ? known : timedOut ? `Time limit exceeded (${limits.timeMs / 1e3} s).` : `The code couldn't run: ${message}` });
|
|
344
|
+
} finally {
|
|
345
|
+
try {
|
|
346
|
+
vm?.dispose();
|
|
347
|
+
runtime.dispose();
|
|
348
|
+
} catch {
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
var PAGE_BYTES = 64 * 1024;
|
|
353
|
+
var INITIAL_PAGES = 256;
|
|
354
|
+
async function runExerciseCaseIsolated(newModule, options) {
|
|
355
|
+
const limits = options.limits ?? EXERCISE_LIMITS;
|
|
356
|
+
const maximum = Math.max(INITIAL_PAGES, Math.floor(limits.memoryBytes / PAGE_BYTES));
|
|
357
|
+
const module = await newModule(new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum }));
|
|
358
|
+
return runExerciseCase(module, { ...options, limits });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ../protocol/src/code-exercise-python.ts
|
|
362
|
+
var SIGINT = 2;
|
|
363
|
+
var FILENAME2 = "solution.py";
|
|
364
|
+
var HARNESS = String.raw`
|
|
365
|
+
import builtins as _mivra_builtins, io as _mivra_io, json as _mivra_json, sys as _mivra_sys, traceback as _mivra_traceback
|
|
366
|
+
|
|
367
|
+
for _mivra_name in list(_mivra_sys.modules):
|
|
368
|
+
if _mivra_name == "js" or _mivra_name.startswith("js.") or _mivra_name == "pyodide_js" or _mivra_name.startswith("pyodide_js."):
|
|
369
|
+
del _mivra_sys.modules[_mivra_name]
|
|
370
|
+
|
|
371
|
+
_mivra_recursion_limit = _mivra_sys.getrecursionlimit()
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
class _MivraOutputLimit(BaseException):
|
|
375
|
+
pass
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
class _MivraSink:
|
|
379
|
+
def __init__(self, limit):
|
|
380
|
+
self.limit = limit
|
|
381
|
+
self.parts = ([], [])
|
|
382
|
+
self.used = 0
|
|
383
|
+
self.exceeded = False
|
|
384
|
+
|
|
385
|
+
def write(self, stream, text):
|
|
386
|
+
if self.exceeded:
|
|
387
|
+
raise _MivraOutputLimit()
|
|
388
|
+
room = self.limit - self.used
|
|
389
|
+
if len(text) > room:
|
|
390
|
+
self.exceeded = True
|
|
391
|
+
text = text[: max(0, room)]
|
|
392
|
+
self.parts[stream].append(text)
|
|
393
|
+
self.used += len(text)
|
|
394
|
+
if self.exceeded:
|
|
395
|
+
raise _MivraOutputLimit()
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
class _MivraStream(_mivra_io.TextIOBase):
|
|
399
|
+
def __init__(self, sink, stream):
|
|
400
|
+
self._sink = sink
|
|
401
|
+
self._stream = stream
|
|
402
|
+
|
|
403
|
+
def writable(self):
|
|
404
|
+
return True
|
|
405
|
+
|
|
406
|
+
def write(self, text):
|
|
407
|
+
if not isinstance(text, str):
|
|
408
|
+
raise TypeError("write() argument must be str, not " + type(text).__name__)
|
|
409
|
+
self._sink.write(self._stream, text)
|
|
410
|
+
return len(text)
|
|
411
|
+
|
|
412
|
+
def flush(self):
|
|
413
|
+
pass
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _mivra_describe(error):
|
|
417
|
+
name = type(error).__name__
|
|
418
|
+
text = str(error)
|
|
419
|
+
message = name + ": " + text if text else name
|
|
420
|
+
line = None
|
|
421
|
+
if isinstance(error, SyntaxError) and error.filename == "${FILENAME2}":
|
|
422
|
+
line = error.lineno
|
|
423
|
+
for frame, lineno in _mivra_traceback.walk_tb(error.__traceback__):
|
|
424
|
+
if frame.f_code.co_filename == "${FILENAME2}":
|
|
425
|
+
line = lineno
|
|
426
|
+
return message + (" (line " + str(line) + ")" if line else "")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _mivra_run(code, function_name, kind, stdin, args_json, output_limit):
|
|
430
|
+
sink = _MivraSink(output_limit)
|
|
431
|
+
result = {}
|
|
432
|
+
_mivra_sys.setrecursionlimit(_mivra_recursion_limit)
|
|
433
|
+
_mivra_sys.stdin = _mivra_io.StringIO(stdin)
|
|
434
|
+
_mivra_sys.stdout = _MivraStream(sink, 0)
|
|
435
|
+
_mivra_sys.stderr = _MivraStream(sink, 1)
|
|
436
|
+
try:
|
|
437
|
+
namespace = {"__name__": "__main__", "__builtins__": _mivra_builtins}
|
|
438
|
+
exec(compile(code, "${FILENAME2}", "exec"), namespace)
|
|
439
|
+
if kind == "call":
|
|
440
|
+
function = namespace.get(function_name)
|
|
441
|
+
if not callable(function):
|
|
442
|
+
raise TypeError(function_name + " is not defined as a function")
|
|
443
|
+
value = function(*_mivra_json.loads(args_json))
|
|
444
|
+
try:
|
|
445
|
+
returned = _mivra_json.dumps(value, allow_nan=False)
|
|
446
|
+
except (TypeError, ValueError) as error:
|
|
447
|
+
result["status"] = "error"
|
|
448
|
+
result["message"] = "The return value can't be recorded as JSON: " + type(error).__name__ + ": " + str(error)
|
|
449
|
+
else:
|
|
450
|
+
if len(returned) > output_limit:
|
|
451
|
+
result["status"] = "error"
|
|
452
|
+
result["message"] = "The return value is too large (over {:,} characters).".format(output_limit)
|
|
453
|
+
else:
|
|
454
|
+
result["returned"] = returned
|
|
455
|
+
except SystemExit as error:
|
|
456
|
+
if kind == "call":
|
|
457
|
+
result["status"] = "error"
|
|
458
|
+
result["message"] = "The code called exit() instead of returning."
|
|
459
|
+
elif error.code not in (None, 0):
|
|
460
|
+
result["status"] = "error"
|
|
461
|
+
result["message"] = "The program exited with status " + str(error.code) + "."
|
|
462
|
+
except _MivraOutputLimit:
|
|
463
|
+
result["status"] = "output"
|
|
464
|
+
except KeyboardInterrupt:
|
|
465
|
+
result["status"] = "time"
|
|
466
|
+
except RecursionError:
|
|
467
|
+
result["status"] = "stack"
|
|
468
|
+
except MemoryError:
|
|
469
|
+
result["status"] = "memory"
|
|
470
|
+
except BaseException as error:
|
|
471
|
+
result["status"] = "error"
|
|
472
|
+
result["message"] = _mivra_describe(error)
|
|
473
|
+
finally:
|
|
474
|
+
_mivra_sys.stdin = _mivra_sys.__stdin__
|
|
475
|
+
_mivra_sys.stdout = _mivra_sys.__stdout__
|
|
476
|
+
_mivra_sys.stderr = _mivra_sys.__stderr__
|
|
477
|
+
result["stdout"] = "".join(sink.parts[0])
|
|
478
|
+
result["stderr"] = "".join(sink.parts[1])
|
|
479
|
+
result["exceeded"] = sink.exceeded
|
|
480
|
+
return _mivra_json.dumps(result)
|
|
481
|
+
`;
|
|
482
|
+
var timeLimit = (ms) => `Time limit exceeded (${ms / 1e3} s): the code ran too long, or never stopped.`;
|
|
483
|
+
function createPythonCaseRunner(pyodide, { now = Date.now } = {}) {
|
|
484
|
+
let deadline = Number.NEGATIVE_INFINITY;
|
|
485
|
+
let interrupted = false;
|
|
486
|
+
const buffer = new Proxy([0], {
|
|
487
|
+
get(target, key) {
|
|
488
|
+
if (key !== "0") return Reflect.get(target, key);
|
|
489
|
+
if (now() <= deadline) return 0;
|
|
490
|
+
interrupted = true;
|
|
491
|
+
return SIGINT;
|
|
492
|
+
},
|
|
493
|
+
set: () => true
|
|
494
|
+
});
|
|
495
|
+
for (const name of ["js", "pyodide_js"]) {
|
|
496
|
+
try {
|
|
497
|
+
pyodide.unregisterJsModule(name);
|
|
498
|
+
} catch {
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
pyodide.runPython(HARNESS);
|
|
502
|
+
const harness = pyodide.runPython("_mivra_run");
|
|
503
|
+
pyodide.setInterruptBuffer(buffer);
|
|
504
|
+
let broken = false;
|
|
505
|
+
return {
|
|
506
|
+
get broken() {
|
|
507
|
+
return broken;
|
|
508
|
+
},
|
|
509
|
+
run({ code, functionName, testCase, limits = EXERCISE_LIMITS }) {
|
|
510
|
+
const finish = (run) => ({
|
|
511
|
+
stdout: run.stdout ?? "",
|
|
512
|
+
...run.stderr ? { stderr: run.stderr } : {},
|
|
513
|
+
...run.returned !== void 0 ? { returned: run.returned } : {},
|
|
514
|
+
...run.error !== void 0 ? { error: run.error.slice(0, MAX_CASE_ERROR_CHARS) } : {}
|
|
515
|
+
});
|
|
516
|
+
if (broken) return finish({ error: "Python stopped working after an earlier case, so this one couldn't run." });
|
|
517
|
+
interrupted = false;
|
|
518
|
+
deadline = now() + limits.timeMs;
|
|
519
|
+
let raw;
|
|
520
|
+
try {
|
|
521
|
+
raw = harness(code, functionName ?? "", testCase.kind, testCase.kind === "stdio" ? testCase.stdin : "", testCase.kind === "call" ? testCase.args : "[]", limits.outputChars);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
if (interrupted) return finish({ error: timeLimit(limits.timeMs) });
|
|
524
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
525
|
+
if (/fatal error/i.test(message)) broken = true;
|
|
526
|
+
return finish({ error: /maximum call stack|too much recursion/i.test(message) ? STACK_EXCEEDED : `The code couldn't run: ${message}` });
|
|
527
|
+
} finally {
|
|
528
|
+
deadline = Number.NEGATIVE_INFINITY;
|
|
529
|
+
}
|
|
530
|
+
const result = JSON.parse(raw);
|
|
531
|
+
const output = { stdout: result.stdout, stderr: result.stderr };
|
|
532
|
+
if (result.exceeded || result.status === "output") return finish({ ...output, error: OUTPUT_EXCEEDED(limits.outputChars) });
|
|
533
|
+
if (result.status === "time" || interrupted) return finish({ ...output, error: timeLimit(limits.timeMs) });
|
|
534
|
+
if (result.status === "stack") return finish({ ...output, error: STACK_EXCEEDED });
|
|
535
|
+
if (result.status === "memory") return finish({ ...output, error: "Memory limit exceeded: the code used more memory than the browser allows." });
|
|
536
|
+
if (result.status === "error") return finish({ ...output, error: result.message ?? "The code raised an error." });
|
|
537
|
+
return finish({ ...output, returned: result.returned });
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ../protocol/src/index.ts
|
|
543
|
+
import { z as z18 } from "zod";
|
|
544
|
+
|
|
545
|
+
// ../protocol/src/artifact-math-input.ts
|
|
546
|
+
import "zod";
|
|
547
|
+
|
|
548
|
+
// ../protocol/src/math-text.ts
|
|
549
|
+
var isSpace = (char) => char !== void 0 && /\s/.test(char);
|
|
550
|
+
var isDigit = (char) => char !== void 0 && char >= "0" && char <= "9";
|
|
551
|
+
function splitMath(source) {
|
|
552
|
+
const pieces = [];
|
|
553
|
+
let literal = "";
|
|
554
|
+
let i = 0;
|
|
555
|
+
while (i < source.length) {
|
|
556
|
+
const char = source[i];
|
|
557
|
+
if (char === "\\" && source[i + 1] === "$") {
|
|
558
|
+
literal += "$";
|
|
559
|
+
i += 2;
|
|
560
|
+
} else if (char !== "$") {
|
|
561
|
+
literal += char;
|
|
562
|
+
i += 1;
|
|
563
|
+
} else if (source[i + 1] === "$") {
|
|
564
|
+
while (source[i] === "$") {
|
|
565
|
+
literal += "$";
|
|
566
|
+
i += 1;
|
|
567
|
+
}
|
|
568
|
+
} else {
|
|
569
|
+
const close = closingDollar(source, i);
|
|
570
|
+
if (close === void 0) {
|
|
571
|
+
literal += "$";
|
|
572
|
+
i += 1;
|
|
573
|
+
} else {
|
|
574
|
+
if (literal) pieces.push({ text: literal });
|
|
575
|
+
literal = "";
|
|
576
|
+
pieces.push({ formula: source.slice(i + 1, close) });
|
|
577
|
+
i = close + 1;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (literal) pieces.push({ text: literal });
|
|
582
|
+
return pieces;
|
|
583
|
+
}
|
|
584
|
+
function closingDollar(source, open) {
|
|
585
|
+
let close = open + 1;
|
|
586
|
+
while (close < source.length && source[close] !== "$") {
|
|
587
|
+
close += source[close] === "\\" && (source[close + 1] === "$" || source[close + 1] === "\\") ? 2 : 1;
|
|
588
|
+
}
|
|
589
|
+
if (close >= source.length || close === open + 1 || source[close + 1] === "$") return void 0;
|
|
590
|
+
if (isSpace(source[open + 1]) || isSpace(source[close - 1]) || isDigit(source[close + 1])) return void 0;
|
|
591
|
+
return /`|\n\s*\n/.test(source.slice(open, close)) ? void 0 : close;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ../protocol/src/artifact-math-input.ts
|
|
595
|
+
var REPAIR = String.raw`Wrap LaTeX commands in single-dollar math delimiters, with no spaces inside: $\displaystyle\sum_{i=1}^{n} i$. Put \displaystyle inside the dollars. For literal backslashes followed by two or more letters (such as C:\Users), use forward slashes, Unicode symbols such as ∖, or describe them in words; backticks do not escape artifact math. Correct the affected field and retry this tool call.`;
|
|
596
|
+
function checkMathText(value, path, ctx) {
|
|
597
|
+
if (typeof value === "string" && splitMath(value).some((piece) => "text" in piece && /\\[a-zA-Z]{2,}/.test(piece.text))) {
|
|
598
|
+
ctx.addIssue({ code: "custom", path, message: REPAIR });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function artifactMathInput(schema, fields, extra) {
|
|
602
|
+
return schema.superRefine((spec, ctx) => {
|
|
603
|
+
const visit = (value, parts, path) => {
|
|
604
|
+
if (parts.length === 0) return checkMathText(value, path, ctx);
|
|
605
|
+
const [key, ...rest] = parts;
|
|
606
|
+
if (key === "*" && Array.isArray(value)) value.forEach((item, i) => visit(item, rest, [...path, i]));
|
|
607
|
+
else if (value && typeof value === "object" && key !== void 0) visit(value[key], rest, [...path, key]);
|
|
608
|
+
};
|
|
609
|
+
for (const field of fields) visit(spec, field.split("."), []);
|
|
610
|
+
extra?.(spec, ctx);
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// ../protocol/src/algorithm-trace.ts
|
|
615
|
+
import { z as z3 } from "zod";
|
|
616
|
+
var MAX_VALUES = 64;
|
|
617
|
+
var MAX_STEPS = 200;
|
|
618
|
+
var MAX_CODE_LINES = 40;
|
|
619
|
+
var MAX_CODE_LINE_LENGTH = 120;
|
|
620
|
+
var MAX_CODE_CHARS = 4e3;
|
|
621
|
+
function codeLines(source) {
|
|
622
|
+
return source.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n");
|
|
623
|
+
}
|
|
624
|
+
var Label = z3.string().trim().min(1).max(40);
|
|
625
|
+
var Cell = z3.union([z3.number(), z3.string().max(24)]);
|
|
626
|
+
var Index = z3.number().int().nonnegative();
|
|
627
|
+
var TracePointer = z3.object({
|
|
628
|
+
name: Label.describe('Pointer label shown under the cell, e.g. "left", "right", "mid", "i".'),
|
|
629
|
+
index: Index.describe("0-based index into the sequence as it is at this step.")
|
|
630
|
+
}).strict();
|
|
631
|
+
var TraceRange = z3.object({
|
|
632
|
+
start: Index.describe("0-based start index, inclusive, within the sequence as it is at this step."),
|
|
633
|
+
end: Index.describe("0-based end index, inclusive. Must be >= start and within the sequence."),
|
|
634
|
+
label: Label.optional().describe('Optional label, e.g. "window".'),
|
|
635
|
+
tone: z3.enum(["active", "done", "muted"]).optional().describe("active = current focus, done = finished/sorted, muted = ruled out. Defaults to active.")
|
|
636
|
+
}).strict();
|
|
637
|
+
var TraceVariable = z3.object({
|
|
638
|
+
name: Label,
|
|
639
|
+
value: z3.union([z3.number(), z3.string().max(80), z3.boolean()])
|
|
640
|
+
}).strict();
|
|
641
|
+
var TraceCode = z3.object({
|
|
642
|
+
language: z3.string().trim().min(1).max(30).describe('The language the code is written in, e.g. "Python", "TypeScript", "Java" or "pseudocode". Shown as a label.'),
|
|
643
|
+
source: z3.string().min(1).max(MAX_CODE_CHARS).describe(
|
|
644
|
+
`The code, as plain text with newlines and its real indentation: at most ${MAX_CODE_LINES} lines of at most ${MAX_CODE_LINE_LENGTH} characters. Line 1 is the first line. No Markdown fences.`
|
|
645
|
+
)
|
|
646
|
+
}).strict().superRefine((code, ctx) => {
|
|
647
|
+
const lines = codeLines(code.source);
|
|
648
|
+
if (lines.every((line) => line.trim() === "")) {
|
|
649
|
+
ctx.addIssue({ code: "custom", path: ["source"], message: "source has no code" });
|
|
650
|
+
}
|
|
651
|
+
if (lines.length > MAX_CODE_LINES) {
|
|
652
|
+
ctx.addIssue({ code: "custom", path: ["source"], message: `source has ${lines.length} lines; at most ${MAX_CODE_LINES} are allowed` });
|
|
653
|
+
}
|
|
654
|
+
const long = lines.findIndex((line) => line.length > MAX_CODE_LINE_LENGTH);
|
|
655
|
+
if (long >= 0) {
|
|
656
|
+
ctx.addIssue({ code: "custom", path: ["source"], message: `line ${long + 1} is longer than ${MAX_CODE_LINE_LENGTH} characters` });
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
var TraceStep = z3.object({
|
|
660
|
+
explanation: z3.string().trim().min(1).max(500).describe("What happens in this step, in one or two sentences."),
|
|
661
|
+
values: z3.array(Cell).min(1).max(MAX_VALUES).optional().describe("The whole sequence after this step. Omit unless the values changed (e.g. a swap); omitted means unchanged."),
|
|
662
|
+
pointers: z3.array(TracePointer).max(8).optional().describe("All pointers to show at this step. Not carried over from earlier steps: repeat any that still apply."),
|
|
663
|
+
ranges: z3.array(TraceRange).max(8).optional().describe("All highlighted ranges at this step. Not carried over from earlier steps."),
|
|
664
|
+
variables: z3.array(TraceVariable).max(12).optional().describe("All running state at this step, e.g. current sum, best so far. Not carried over from earlier steps."),
|
|
665
|
+
lines: z3.array(z3.number().int().positive()).max(MAX_CODE_LINES).optional().describe(
|
|
666
|
+
"Only with code: the 1-based line numbers in code.source this step is running, highlighted beside the values. Not carried over from earlier steps; omit or leave empty to highlight none."
|
|
667
|
+
)
|
|
668
|
+
}).strict();
|
|
669
|
+
var AlgorithmTraceSpec = z3.object({
|
|
670
|
+
title: z3.string().trim().min(1).max(120),
|
|
671
|
+
values: z3.array(Cell).min(1).max(MAX_VALUES).describe("The input sequence before the first step."),
|
|
672
|
+
code: TraceCode.optional().describe(
|
|
673
|
+
"Optional source code shown beside the values, with each step's `lines` highlighted. Include it only when the code itself is the point."
|
|
674
|
+
),
|
|
675
|
+
steps: z3.array(TraceStep).min(1).max(MAX_STEPS)
|
|
676
|
+
}).strict().superRefine((spec, ctx) => {
|
|
677
|
+
let length = spec.values.length;
|
|
678
|
+
const codeLength = spec.code ? codeLines(spec.code.source).length : 0;
|
|
679
|
+
spec.steps.forEach((step, i) => {
|
|
680
|
+
if (step.lines && !spec.code) {
|
|
681
|
+
ctx.addIssue({ code: "custom", path: ["steps", i, "lines"], message: "lines need code: add code, or remove lines" });
|
|
682
|
+
} else {
|
|
683
|
+
step.lines?.forEach((line, j) => {
|
|
684
|
+
if (line > codeLength) {
|
|
685
|
+
ctx.addIssue({
|
|
686
|
+
code: "custom",
|
|
687
|
+
path: ["steps", i, "lines", j],
|
|
688
|
+
message: `line ${line} is outside the code (${codeLength} lines)`
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
if (step.values) length = step.values.length;
|
|
694
|
+
step.pointers?.forEach((p, j) => {
|
|
695
|
+
if (p.index >= length) {
|
|
696
|
+
ctx.addIssue({
|
|
697
|
+
code: "custom",
|
|
698
|
+
path: ["steps", i, "pointers", j, "index"],
|
|
699
|
+
message: `index ${p.index} is outside the sequence (length ${length})`
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
step.ranges?.forEach((r, j) => {
|
|
704
|
+
if (r.end >= length || r.start > r.end) {
|
|
705
|
+
ctx.addIssue({
|
|
706
|
+
code: "custom",
|
|
707
|
+
path: ["steps", i, "ranges", j],
|
|
708
|
+
message: `range ${r.start}..${r.end} is invalid for a sequence of length ${length}`
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
});
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
// ../protocol/src/code-walkthrough.ts
|
|
716
|
+
import { z as z4 } from "zod";
|
|
717
|
+
var MAX_WALKTHROUGH_STEPS = 200;
|
|
718
|
+
var MAX_WALKTHROUGH_VARIABLES = 12;
|
|
719
|
+
var MAX_WALKTHROUGH_OUTPUT = 4e3;
|
|
720
|
+
var CodeWalkthroughStep = z4.object({
|
|
721
|
+
explanation: z4.string().trim().min(1).max(500).describe("What happens at this step and why, in one or two sentences."),
|
|
722
|
+
label: z4.string().trim().min(1).max(80).optional().describe('Optional short name for the step, e.g. "Initial render", "Click handler", "Render 2".'),
|
|
723
|
+
lines: z4.array(z4.number().int().positive()).max(MAX_CODE_LINES).optional().describe("The 1-based line numbers in code.source this step is at. Not carried over: omit or leave empty to highlight none."),
|
|
724
|
+
variables: z4.array(TraceVariable).max(MAX_WALKTHROUGH_VARIABLES).describe(
|
|
725
|
+
'All the state visible at this step, each name once, e.g. "n", "render.count", "handler.count", "queued update". Not carried over: list everything that still applies, or [] for none. Values are plain text, numbers or booleans; write undefined, null or a short object as a string.'
|
|
726
|
+
),
|
|
727
|
+
output: z4.string().max(MAX_WALKTHROUGH_OUTPUT).describe(
|
|
728
|
+
'Everything visible as output at this step, as plain text, e.g. printed lines or what the page shows ("Count: 0"). Not carried over: repeat earlier output that is still visible, or "" for none.'
|
|
729
|
+
)
|
|
730
|
+
}).strict();
|
|
731
|
+
var CodeWalkthroughSpec = z4.object({
|
|
732
|
+
title: z4.string().trim().min(1).max(120),
|
|
733
|
+
code: TraceCode.describe("The source shown on every step. It stays the same across steps."),
|
|
734
|
+
steps: z4.array(CodeWalkthroughStep).min(1).max(MAX_WALKTHROUGH_STEPS)
|
|
735
|
+
}).strict().superRefine((spec, ctx) => {
|
|
736
|
+
const codeLength = codeLines(spec.code.source).length;
|
|
737
|
+
spec.steps.forEach((step, i) => {
|
|
738
|
+
step.lines?.forEach((line, j) => {
|
|
739
|
+
if (line > codeLength) {
|
|
740
|
+
ctx.addIssue({ code: "custom", path: ["steps", i, "lines", j], message: `line ${line} is outside the code (${codeLength} lines)` });
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
const seen = /* @__PURE__ */ new Set();
|
|
744
|
+
step.variables.forEach((variable, j) => {
|
|
745
|
+
if (seen.has(variable.name)) {
|
|
746
|
+
ctx.addIssue({ code: "custom", path: ["steps", i, "variables", j, "name"], message: `variable "${variable.name}" appears twice in this step` });
|
|
747
|
+
}
|
|
748
|
+
seen.add(variable.name);
|
|
749
|
+
});
|
|
750
|
+
});
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
// ../protocol/src/composition.ts
|
|
754
|
+
import { z as z5 } from "zod";
|
|
755
|
+
var MAX_COMPOSITION_GROUPS = 4;
|
|
756
|
+
var MAX_COMPOSITION_ENTITIES = 16;
|
|
757
|
+
var MAX_COMPOSITION_CONNECTIONS = 24;
|
|
758
|
+
var MAX_COMPOSITION_STEPS = 20;
|
|
759
|
+
var MAX_COMPOSITION_PROPERTIES = 6;
|
|
760
|
+
var MAX_COMPOSITION_BLOCKS = 2;
|
|
761
|
+
var MAX_COMPOSITION_CALLOUTS = 2;
|
|
762
|
+
var MAX_COMPOSITION_CODE_LINES = 12;
|
|
763
|
+
var MAX_COMPOSITION_CODE_LINE_LENGTH = 80;
|
|
764
|
+
var MAX_COMPOSITION_ENTITY_BODY = 1e3;
|
|
765
|
+
var MAX_COMPOSITION_BODY = 4e3;
|
|
766
|
+
var Id = z5.string().trim().min(1).max(24);
|
|
767
|
+
var Label2 = z5.string().trim().min(1).max(32);
|
|
768
|
+
var CompositionTone = z5.enum(["active", "done", "muted"]);
|
|
769
|
+
var CompositionProperty = z5.object({
|
|
770
|
+
name: Label2.describe("Literal property name, unique within its list. Not a formula."),
|
|
771
|
+
value: z5.union([z5.number(), z5.boolean(), z5.string().max(64)]).describe('A number, a boolean or literal text of at most 64 characters ("" is allowed). Never Markdown or a formula; write a list or object as short text.')
|
|
772
|
+
}).strict();
|
|
773
|
+
var Properties = z5.array(CompositionProperty).max(MAX_COMPOSITION_PROPERTIES);
|
|
774
|
+
var CompositionBlock = z5.discriminatedUnion("type", [
|
|
775
|
+
z5.object({
|
|
776
|
+
type: z5.literal("text"),
|
|
777
|
+
text: z5.string().trim().min(1).max(280).describe("A short note. Only $...$ is a formula; no Markdown.")
|
|
778
|
+
}).strict(),
|
|
779
|
+
z5.object({
|
|
780
|
+
type: z5.literal("code"),
|
|
781
|
+
language: Label2.describe('The language, e.g. "Python" or "bytecode". Shown as a label; any language is accepted.'),
|
|
782
|
+
code: z5.string().overwrite((code) => code.replace(/\r\n?/g, "\n")).min(1).max(MAX_COMPOSITION_CODE_LINES * (MAX_COMPOSITION_CODE_LINE_LENGTH + 1)).describe(
|
|
783
|
+
`Plain text with newlines and its real indentation: at most ${MAX_COMPOSITION_CODE_LINES} lines of at most ${MAX_COMPOSITION_CODE_LINE_LENGTH} characters. No Markdown fences. Never run.`
|
|
784
|
+
)
|
|
785
|
+
}).strict(),
|
|
786
|
+
z5.object({
|
|
787
|
+
type: z5.literal("math"),
|
|
788
|
+
source: z5.string().trim().min(1).max(300).describe("One display formula as LaTeX, without dollar delimiters.")
|
|
789
|
+
}).strict()
|
|
790
|
+
]);
|
|
791
|
+
var CompositionGroup = z5.object({
|
|
792
|
+
id: Id.describe("Unique id, used by each step's placements."),
|
|
793
|
+
label: Label2.describe("The container's name. Only $...$ is a formula."),
|
|
794
|
+
ordered: z5.boolean().describe("True when position matters, as in a queue or stack: the first entity is then the front or top. Say which it is in the step's explanation.")
|
|
795
|
+
}).strict();
|
|
796
|
+
var CompositionEntity = z5.object({
|
|
797
|
+
id: Id.describe("Unique id, used by connections and steps."),
|
|
798
|
+
label: Label2.describe("Short name on the card. Only $...$ is a formula."),
|
|
799
|
+
properties: Properties.describe("The entity's declared properties, in display order; [] for none. A step shows these unless its `state` replaces them."),
|
|
800
|
+
body: z5.array(CompositionBlock).max(MAX_COMPOSITION_BLOCKS).optional().describe(
|
|
801
|
+
`Up to ${MAX_COMPOSITION_BLOCKS} blocks of text, code or maths inside the card, the same on every step. Their text, code and source may total ${MAX_COMPOSITION_ENTITY_BODY} characters per entity and ${MAX_COMPOSITION_BODY} over all entities.`
|
|
802
|
+
)
|
|
803
|
+
}).strict();
|
|
804
|
+
var CompositionConnection = z5.object({
|
|
805
|
+
id: Id.describe("Unique id, listed by each step that shows this connection."),
|
|
806
|
+
from: Id.describe("Id of the entity that holds the reference."),
|
|
807
|
+
to: Id.describe("Id of the entity it refers to. Must differ from `from`."),
|
|
808
|
+
label: Label2.optional().describe('Optional name of the reference, e.g. "next". Only $...$ is a formula.')
|
|
809
|
+
}).strict();
|
|
810
|
+
var CompositionStep = z5.object({
|
|
811
|
+
label: z5.string().trim().min(1).max(80).optional().describe("Optional literal text for the step, shown in monospace, e.g. the statement `b = a`."),
|
|
812
|
+
explanation: z5.string().trim().min(1).max(500).describe("What this step shows and what changed, in one or two sentences."),
|
|
813
|
+
placements: z5.array(
|
|
814
|
+
z5.object({
|
|
815
|
+
groupId: Id,
|
|
816
|
+
entityIds: z5.array(Id).max(MAX_COMPOSITION_ENTITIES).describe("The entities in this group at this step, top to bottom; [] for an empty group.")
|
|
817
|
+
}).strict()
|
|
818
|
+
).max(MAX_COMPOSITION_GROUPS).describe("Exactly one entry for every group, at every step. Not carried over from earlier steps."),
|
|
819
|
+
hidden: z5.array(Id).max(MAX_COMPOSITION_ENTITIES).describe("Every entity not shown at this step, e.g. before it is created. Each entity is in exactly one placement or here."),
|
|
820
|
+
connections: z5.array(Id).max(MAX_COMPOSITION_CONNECTIONS).describe("Ids of the connections shown at this step; [] for none. Not carried over, and both ends must be placed in a group."),
|
|
821
|
+
state: z5.array(z5.object({ entityId: Id, properties: Properties.describe("The entity's whole property list at this step; [] shows none.") }).strict()).max(MAX_COMPOSITION_ENTITIES).optional().describe("Entities whose properties differ from their declaration at this step, at most one entry each. Not carried over: an entity without an entry shows its declared properties again."),
|
|
822
|
+
emphasis: z5.array(
|
|
823
|
+
z5.object({ entityId: Id, tone: CompositionTone.describe("active = current focus, done = finished, muted = ruled out or idle.") }).strict()
|
|
824
|
+
).max(MAX_COMPOSITION_ENTITIES).optional().describe("Entities to emphasise at this step, at most one entry each. Not carried over."),
|
|
825
|
+
callouts: z5.array(z5.object({ entityId: Id, text: z5.string().trim().min(1).max(140).describe("A short note shown inside the card. Only $...$ is a formula.") }).strict()).max(MAX_COMPOSITION_CALLOUTS).optional().describe("Notes on entities at this step, at most one per entity. Not carried over.")
|
|
826
|
+
}).strict();
|
|
827
|
+
function checkProperties(properties, path, ctx) {
|
|
828
|
+
const seen = /* @__PURE__ */ new Set();
|
|
829
|
+
properties.forEach((property, i) => {
|
|
830
|
+
if (seen.has(property.name)) {
|
|
831
|
+
ctx.addIssue({ code: "custom", path: [...path, i, "name"], message: `property "${property.name}" appears twice in this list: keep one, or rename the other` });
|
|
832
|
+
}
|
|
833
|
+
seen.add(property.name);
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
var blockLength = (block) => (block.type === "text" ? block.text : block.type === "code" ? block.code : block.source).length;
|
|
837
|
+
function checkStep(step, i, declared, ctx) {
|
|
838
|
+
const n = i + 1;
|
|
839
|
+
const issue = (path, message) => ctx.addIssue({ code: "custom", path: ["steps", i, ...path], message });
|
|
840
|
+
const groupIds = new Set(declared.groups.map((group) => group.id));
|
|
841
|
+
const entityIds = new Set(declared.entities.map((entity) => entity.id));
|
|
842
|
+
const placedGroups = /* @__PURE__ */ new Set();
|
|
843
|
+
const where = /* @__PURE__ */ new Map();
|
|
844
|
+
const visible = /* @__PURE__ */ new Set();
|
|
845
|
+
const account = (id, place, path) => {
|
|
846
|
+
if (!entityIds.has(id)) return issue(path, `no entity has id "${id}": use a declared entity id`);
|
|
847
|
+
const earlier = where.get(id);
|
|
848
|
+
if (earlier !== void 0) return issue(path, `entity "${id}" is already ${earlier} in step ${n}: list each entity exactly once per step`);
|
|
849
|
+
where.set(id, place);
|
|
850
|
+
};
|
|
851
|
+
step.placements.forEach((placement, j) => {
|
|
852
|
+
if (!groupIds.has(placement.groupId)) issue(["placements", j, "groupId"], `no group has id "${placement.groupId}": use a declared group id`);
|
|
853
|
+
else if (placedGroups.has(placement.groupId)) issue(["placements", j, "groupId"], `group "${placement.groupId}" has two placements in step ${n}: merge them into one`);
|
|
854
|
+
placedGroups.add(placement.groupId);
|
|
855
|
+
placement.entityIds.forEach((id, k) => {
|
|
856
|
+
account(id, `in group "${placement.groupId}"`, ["placements", j, "entityIds", k]);
|
|
857
|
+
if (groupIds.has(placement.groupId) && entityIds.has(id)) visible.add(id);
|
|
858
|
+
});
|
|
859
|
+
});
|
|
860
|
+
for (const group of declared.groups) {
|
|
861
|
+
if (!placedGroups.has(group.id)) issue(["placements"], `step ${n} has no placement for group "${group.id}": add { groupId: "${group.id}", entityIds: [] } if it is empty`);
|
|
862
|
+
}
|
|
863
|
+
step.hidden.forEach((id, j) => {
|
|
864
|
+
account(id, "hidden", ["hidden", j]);
|
|
865
|
+
visible.delete(id);
|
|
866
|
+
});
|
|
867
|
+
for (const entity of declared.entities) {
|
|
868
|
+
if (!where.has(entity.id)) issue([], `entity "${entity.id}" is not accounted for in step ${n}: list it in one placement's entityIds, or in hidden`);
|
|
869
|
+
}
|
|
870
|
+
const shown = /* @__PURE__ */ new Set();
|
|
871
|
+
step.connections.forEach((id, j) => {
|
|
872
|
+
const path = ["connections", j];
|
|
873
|
+
const connection = declared.connections.get(id);
|
|
874
|
+
if (!connection) return issue(path, `no connection has id "${id}": use a declared connection id`);
|
|
875
|
+
if (shown.has(id)) issue(path, `connection "${id}" is listed twice in step ${n}: list it once`);
|
|
876
|
+
shown.add(id);
|
|
877
|
+
for (const end of [connection.from, connection.to]) {
|
|
878
|
+
if (entityIds.has(end) && !visible.has(end)) {
|
|
879
|
+
issue(path, `connection "${id}" needs entity "${end}", which is not placed in a group in step ${n}: place it, or leave the connection out of this step`);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
});
|
|
883
|
+
const targets = (field) => {
|
|
884
|
+
const seen = /* @__PURE__ */ new Set();
|
|
885
|
+
step[field]?.forEach(({ entityId }, j) => {
|
|
886
|
+
const path = [field, j, "entityId"];
|
|
887
|
+
if (!entityIds.has(entityId)) return issue(path, `no entity has id "${entityId}": use a declared entity id`);
|
|
888
|
+
if (seen.has(entityId)) issue(path, `entity "${entityId}" has two ${field} entries in step ${n}: merge them into one`);
|
|
889
|
+
seen.add(entityId);
|
|
890
|
+
if (!visible.has(entityId)) issue(path, `entity "${entityId}" is not placed in a group in step ${n}: place it, or remove this ${field} entry`);
|
|
891
|
+
});
|
|
892
|
+
};
|
|
893
|
+
targets("state");
|
|
894
|
+
targets("emphasis");
|
|
895
|
+
targets("callouts");
|
|
896
|
+
step.state?.forEach((entry, j) => checkProperties(entry.properties, ["steps", i, "state", j, "properties"], ctx));
|
|
897
|
+
}
|
|
898
|
+
var CompositionSpec = z5.object({
|
|
899
|
+
title: z5.string().trim().min(1).max(120),
|
|
900
|
+
groups: z5.array(CompositionGroup).min(1).max(MAX_COMPOSITION_GROUPS).describe("The containers, in reading order. Groups don't nest."),
|
|
901
|
+
entities: z5.array(CompositionEntity).min(1).max(MAX_COMPOSITION_ENTITIES).describe("Everything that is ever shown, declared once. Steps place or hide each one."),
|
|
902
|
+
connections: z5.array(CompositionConnection).max(MAX_COMPOSITION_CONNECTIONS).describe("Every directed reference that is ever shown; [] for none. Two entities may have several, each with its own id."),
|
|
903
|
+
steps: z5.array(CompositionStep).min(1).max(MAX_COMPOSITION_STEPS).describe("Complete snapshots in order. One step makes a static diagram.")
|
|
904
|
+
}).strict().superRefine((spec, ctx) => {
|
|
905
|
+
const usedBy = /* @__PURE__ */ new Map();
|
|
906
|
+
const declare = (id, what, path) => {
|
|
907
|
+
const earlier = usedBy.get(id);
|
|
908
|
+
if (earlier) ctx.addIssue({ code: "custom", path, message: `id "${id}" is already used by a ${earlier}: give every group, entity and connection its own id` });
|
|
909
|
+
else usedBy.set(id, what);
|
|
910
|
+
};
|
|
911
|
+
spec.groups.forEach((group, i) => declare(group.id, "group", ["groups", i, "id"]));
|
|
912
|
+
spec.entities.forEach((entity, i) => declare(entity.id, "entity", ["entities", i, "id"]));
|
|
913
|
+
spec.connections.forEach((connection, i) => declare(connection.id, "connection", ["connections", i, "id"]));
|
|
914
|
+
let bodyTotal = 0;
|
|
915
|
+
spec.entities.forEach((entity, i) => {
|
|
916
|
+
checkProperties(entity.properties, ["entities", i, "properties"], ctx);
|
|
917
|
+
let entityTotal = 0;
|
|
918
|
+
entity.body?.forEach((block, j) => {
|
|
919
|
+
entityTotal += blockLength(block);
|
|
920
|
+
if (block.type !== "code") return;
|
|
921
|
+
const path = ["entities", i, "body", j, "code"];
|
|
922
|
+
const lines = codeLines(block.code);
|
|
923
|
+
if (lines.every((line) => line.trim() === "")) ctx.addIssue({ code: "custom", path, message: "code has no code: write some, or remove the block" });
|
|
924
|
+
if (lines.length > MAX_COMPOSITION_CODE_LINES) {
|
|
925
|
+
ctx.addIssue({ code: "custom", path, message: `code has ${lines.length} lines; at most ${MAX_COMPOSITION_CODE_LINES} are allowed: shorten it` });
|
|
926
|
+
}
|
|
927
|
+
const long = lines.findIndex((line) => line.length > MAX_COMPOSITION_CODE_LINE_LENGTH);
|
|
928
|
+
if (long >= 0) ctx.addIssue({ code: "custom", path, message: `line ${long + 1} is longer than ${MAX_COMPOSITION_CODE_LINE_LENGTH} characters: break or shorten it` });
|
|
929
|
+
});
|
|
930
|
+
bodyTotal += entityTotal;
|
|
931
|
+
if (entityTotal > MAX_COMPOSITION_ENTITY_BODY) {
|
|
932
|
+
ctx.addIssue({
|
|
933
|
+
code: "custom",
|
|
934
|
+
path: ["entities", i, "body"],
|
|
935
|
+
message: `entity "${entity.id}" has ${entityTotal} characters of body content; at most ${MAX_COMPOSITION_ENTITY_BODY} are allowed: shorten its blocks`
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
if (bodyTotal > MAX_COMPOSITION_BODY) {
|
|
940
|
+
ctx.addIssue({ code: "custom", path: ["entities"], message: `the bodies total ${bodyTotal} characters; at most ${MAX_COMPOSITION_BODY} are allowed: shorten or remove some` });
|
|
941
|
+
}
|
|
942
|
+
const entityIds = new Set(spec.entities.map((entity) => entity.id));
|
|
943
|
+
spec.connections.forEach((connection, i) => {
|
|
944
|
+
for (const end of ["from", "to"]) {
|
|
945
|
+
if (!entityIds.has(connection[end])) {
|
|
946
|
+
ctx.addIssue({ code: "custom", path: ["connections", i, end], message: `no entity has id "${connection[end]}": connections join declared entities` });
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
if (connection.from === connection.to) {
|
|
950
|
+
ctx.addIssue({ code: "custom", path: ["connections", i, "to"], message: `connection "${connection.id}" joins "${connection.from}" to itself: its ends must be two different entities` });
|
|
951
|
+
}
|
|
952
|
+
});
|
|
953
|
+
const declared = { groups: spec.groups, entities: spec.entities, connections: new Map(spec.connections.map((connection) => [connection.id, connection])) };
|
|
954
|
+
spec.steps.forEach((step, i) => checkStep(step, i, declared, ctx));
|
|
955
|
+
});
|
|
956
|
+
var DESCRIPTION = "Show the learner where things are: entities as cards inside named groups, the references between them, and how that changes step by step. Use it for location, sharing and changing contents, such as two variables referring to one object (aliasing), values moving through pipeline stages, or tasks moving between a queue and a stack. Declare every group, entity and connection once, then give each step as a complete snapshot: one placement for every group (entityIds may be []), every other entity in `hidden`, and the ids of the connections shown. Nothing carries over between steps, so repeat whatever still applies; `state` replaces an entity's whole property list for that step only, and without it the entity shows its declared properties again. In an ordered group the first entity is the front or top: say in the explanation which end is which. Keep it small (roughly 3-8 entities and 3-8 steps) and make each explanation say what changed and why. Never give coordinates or styles: the layout is automatic. Code in a body is inert text. Use show_graph instead for topology, state machines, flowcharts, trees and graph algorithms, show_algorithm_trace for an algorithm over a sequence, show_code_walkthrough to explain source lines, show_table for tabular comparison, and show_set_diagram or show_worked_steps for sets and proofs.";
|
|
957
|
+
var compositionArtifactKind = {
|
|
958
|
+
version: 1,
|
|
959
|
+
toolName: "show_composition",
|
|
960
|
+
description: DESCRIPTION,
|
|
961
|
+
spec: CompositionSpec,
|
|
962
|
+
// Code, ids, languages, property strings, step labels and display formulas are literal: no math check.
|
|
963
|
+
input: artifactMathInput(CompositionSpec, [
|
|
964
|
+
"title",
|
|
965
|
+
"groups.*.label",
|
|
966
|
+
"entities.*.label",
|
|
967
|
+
"entities.*.body.*.text",
|
|
968
|
+
"connections.*.label",
|
|
969
|
+
"steps.*.explanation",
|
|
970
|
+
"steps.*.callouts.*.text"
|
|
971
|
+
])
|
|
972
|
+
};
|
|
973
|
+
var CompositionArtifactView = z5.object({ id: z5.string(), createdAt: z5.string().datetime(), kind: z5.literal("composition"), version: z5.literal(1), spec: CompositionSpec }).strict();
|
|
974
|
+
|
|
975
|
+
// ../protocol/src/course.ts
|
|
976
|
+
import { z as z6 } from "zod";
|
|
977
|
+
var MAX_GOAL_CHARS = 300;
|
|
978
|
+
var CourseGoal = z6.string().trim().min(1).max(MAX_GOAL_CHARS);
|
|
979
|
+
var COURSE_KINDS = ["lessons", "project"];
|
|
980
|
+
var CourseKind = z6.enum(COURSE_KINDS);
|
|
981
|
+
var StartCourse = z6.object({ goal: CourseGoal, kind: CourseKind.optional() }).strict();
|
|
982
|
+
var ConceptName = z6.string().trim().min(1).max(80);
|
|
983
|
+
var PlacementQuestionSpec = z6.object({
|
|
984
|
+
concept: ConceptName.describe(`The single concept this question probes, e.g. "chain rule". Reuse the exact name from the learner's record when it is there.`),
|
|
985
|
+
question: z6.string().trim().min(1).max(1e3),
|
|
986
|
+
options: z6.array(z6.object({ text: z6.string().trim().min(1).max(300) }).strict()).min(2).max(5).describe('2-5 options with distinct text. For true/false or yes/no use two options, e.g. "True" and "False". Never add a "Not sure" option: the UI always offers one.'),
|
|
987
|
+
correctOptionIndex: z6.number().int().nonnegative().describe("0-based index of the single correct option."),
|
|
988
|
+
explanation: z6.string().trim().min(1).max(600).describe("One or two sentences shown after answering: why the correct option is correct.")
|
|
989
|
+
}).strict().superRefine((spec, ctx) => {
|
|
990
|
+
if (spec.correctOptionIndex >= spec.options.length) {
|
|
991
|
+
ctx.addIssue({ code: "custom", path: ["correctOptionIndex"], message: "correctOptionIndex must point at one of the options" });
|
|
992
|
+
}
|
|
993
|
+
const seen = /* @__PURE__ */ new Map();
|
|
994
|
+
spec.options.forEach((option, i) => {
|
|
995
|
+
const key = option.text.normalize("NFC");
|
|
996
|
+
const first = seen.get(key);
|
|
997
|
+
if (first !== void 0) ctx.addIssue({ code: "custom", path: ["options", i, "text"], message: `duplicates option ${first}` });
|
|
998
|
+
else seen.set(key, i);
|
|
999
|
+
if (/^\s*(not sure|i don'?t know|unsure|skip)\W*$/i.test(option.text)) {
|
|
1000
|
+
ctx.addIssue({ code: "custom", path: ["options", i, "text"], message: "Leave out Not sure / Skip: the UI always offers them" });
|
|
1001
|
+
}
|
|
1002
|
+
});
|
|
1003
|
+
});
|
|
1004
|
+
var PlacementQuestionPublic = z6.object({ concept: z6.string(), question: z6.string(), options: z6.array(z6.object({ text: z6.string() }).strict()) }).strict();
|
|
1005
|
+
var toPlacementQuestionPublic = (spec) => ({
|
|
1006
|
+
concept: spec.concept,
|
|
1007
|
+
question: spec.question,
|
|
1008
|
+
options: spec.options.map((o) => ({ text: o.text }))
|
|
1009
|
+
});
|
|
1010
|
+
var PlacementAnswer = z6.union([
|
|
1011
|
+
z6.object({ optionIndex: z6.number().int().nonnegative() }).strict(),
|
|
1012
|
+
z6.object({ unsure: z6.literal(true) }).strict(),
|
|
1013
|
+
z6.object({ skipped: z6.literal(true) }).strict()
|
|
1014
|
+
]);
|
|
1015
|
+
var PlacementResult = z6.enum(["correct", "incorrect", "unsure", "skipped"]);
|
|
1016
|
+
var PlacementGrade = z6.object({ result: PlacementResult, correctOptionIndex: z6.number().int().nonnegative(), explanation: z6.string() }).strict();
|
|
1017
|
+
function gradePlacementQuestion(spec, answer) {
|
|
1018
|
+
let result;
|
|
1019
|
+
if ("optionIndex" in answer) {
|
|
1020
|
+
if (!spec.options[answer.optionIndex]) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);
|
|
1021
|
+
result = answer.optionIndex === spec.correctOptionIndex ? "correct" : "incorrect";
|
|
1022
|
+
} else result = "unsure" in answer ? "unsure" : "skipped";
|
|
1023
|
+
return { result, correctOptionIndex: spec.correctOptionIndex, explanation: spec.explanation };
|
|
1024
|
+
}
|
|
1025
|
+
var MAX_INTERVIEW_CONTEXT_CHARS = 2e3;
|
|
1026
|
+
var InterviewContextSpec = z6.object({
|
|
1027
|
+
question: z6.string().trim().min(1).max(300).describe(`The question, e.g. "Anything else you'd like us to know about what you already understand or what you want to explore?"`)
|
|
1028
|
+
}).strict();
|
|
1029
|
+
var InterviewContextAnswer = z6.union([
|
|
1030
|
+
z6.object({ text: z6.string().trim().max(MAX_INTERVIEW_CONTEXT_CHARS) }).strict(),
|
|
1031
|
+
z6.object({ skipped: z6.literal(true) }).strict()
|
|
1032
|
+
]);
|
|
1033
|
+
var InterviewContextGrade = z6.object({ result: z6.enum(["answered", "skipped"]) }).strict();
|
|
1034
|
+
var gradeInterviewContext = (answer) => ({
|
|
1035
|
+
result: "text" in answer && answer.text.length > 0 ? "answered" : "skipped"
|
|
1036
|
+
});
|
|
1037
|
+
var KnownSource = z6.enum(["memory", "test", "guess"]);
|
|
1038
|
+
var SyllabusTopicInput = z6.object({
|
|
1039
|
+
title: z6.string().trim().min(1).max(120),
|
|
1040
|
+
summary: z6.string().trim().min(1).max(400).describe("What the lesson on this topic will cover, in one or two sentences."),
|
|
1041
|
+
reason: z6.string().trim().min(1).max(300).describe('Why this topic is here for this learner, e.g. "You missed the question on local minima".'),
|
|
1042
|
+
requestedByLearner: z6.boolean().describe("True if the learner explicitly asked for this topic. Such topics are never removed automatically."),
|
|
1043
|
+
concepts: z6.array(ConceptName).min(1).max(8).describe("Concept names this topic teaches; reuse names from the learner's record and the placement questions.")
|
|
1044
|
+
}).strict();
|
|
1045
|
+
var courseIcons = [
|
|
1046
|
+
"sigma",
|
|
1047
|
+
"calculator",
|
|
1048
|
+
"code",
|
|
1049
|
+
"terminal",
|
|
1050
|
+
"cpu",
|
|
1051
|
+
"database",
|
|
1052
|
+
"network",
|
|
1053
|
+
"shield",
|
|
1054
|
+
"flask-conical",
|
|
1055
|
+
"atom",
|
|
1056
|
+
"dna",
|
|
1057
|
+
"leaf",
|
|
1058
|
+
"telescope",
|
|
1059
|
+
"globe",
|
|
1060
|
+
"landmark",
|
|
1061
|
+
"book-open",
|
|
1062
|
+
"pen-tool",
|
|
1063
|
+
"languages",
|
|
1064
|
+
"music",
|
|
1065
|
+
"palette",
|
|
1066
|
+
"camera",
|
|
1067
|
+
"brain",
|
|
1068
|
+
"users",
|
|
1069
|
+
"chart-line",
|
|
1070
|
+
"briefcase",
|
|
1071
|
+
"scale",
|
|
1072
|
+
"stethoscope",
|
|
1073
|
+
"heart-pulse",
|
|
1074
|
+
"wrench",
|
|
1075
|
+
"dumbbell"
|
|
1076
|
+
];
|
|
1077
|
+
var CourseIcon = z6.enum(courseIcons);
|
|
1078
|
+
var COURSE_TITLE_MAX = 60;
|
|
1079
|
+
var SyllabusInput = z6.object({
|
|
1080
|
+
// Bad values parse as missing rather than failing the call: a syllabus is worth more than its label (#58).
|
|
1081
|
+
title: z6.string().trim().min(1).max(COURSE_TITLE_MAX).optional().catch(void 0).describe('A short name for the course, 2-5 words, shown in the sidebar, e.g. "Discrete Math: Induction". Name what the syllabus covers, not the request.'),
|
|
1082
|
+
icon: CourseIcon.optional().catch(void 0).describe("The subject icon that best fits the course: sigma = maths, calculator = arithmetic or accounting, code/terminal = programming, cpu = hardware, flask-conical = chemistry, atom = physics, dna = biology, leaf = ecology, telescope = astronomy, globe = geography, landmark = history, book-open = literature, pen-tool = writing, languages = languages, palette = art, brain = psychology, users = sociology, chart-line = economics or statistics, briefcase = business, scale = law, stethoscope/heart-pulse = medicine, wrench = engineering, dumbbell = sport."),
|
|
1083
|
+
topics: z6.array(SyllabusTopicInput).min(1).max(20).describe("The ordered topics, first to learn first. Each topic gets one lesson."),
|
|
1084
|
+
known: z6.array(
|
|
1085
|
+
z6.object({
|
|
1086
|
+
concept: ConceptName,
|
|
1087
|
+
source: KnownSource.describe("memory = from their record or memories; test = from this placement interview; guess = your inference"),
|
|
1088
|
+
note: z6.string().trim().min(1).max(200)
|
|
1089
|
+
}).strict()
|
|
1090
|
+
).max(20).describe("What the learner already knows or doesn't, each labelled with where that comes from. Shown to the learner.")
|
|
1091
|
+
}).strict().superRefine((input, ctx) => {
|
|
1092
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1093
|
+
input.topics.forEach((topic, i) => {
|
|
1094
|
+
const key = topic.title.trim().toLowerCase();
|
|
1095
|
+
if (seen.has(key)) ctx.addIssue({ code: "custom", path: ["topics", i, "title"], message: "Topic titles must be distinct" });
|
|
1096
|
+
seen.add(key);
|
|
1097
|
+
});
|
|
1098
|
+
});
|
|
1099
|
+
var SyllabusTopic = SyllabusTopicInput.extend({ id: z6.string() }).strict();
|
|
1100
|
+
var SyllabusView = z6.object({
|
|
1101
|
+
version: z6.number().int().positive(),
|
|
1102
|
+
source: z6.enum(["interview", "tutor", "adaptive", "undo"]),
|
|
1103
|
+
reason: z6.string().nullable(),
|
|
1104
|
+
changedTopicIds: z6.array(z6.string()),
|
|
1105
|
+
/** Whether the learner can undo this version: an automatic change none of whose new topics has started. */
|
|
1106
|
+
canUndo: z6.boolean(),
|
|
1107
|
+
topics: z6.array(SyllabusTopic),
|
|
1108
|
+
known: SyllabusInput.shape.known,
|
|
1109
|
+
createdAt: z6.string().datetime()
|
|
1110
|
+
}).strict();
|
|
1111
|
+
var CourseStatus = z6.enum(["interviewing", "active", "complete"]);
|
|
1112
|
+
var CourseView = z6.object({
|
|
1113
|
+
id: z6.string(),
|
|
1114
|
+
sessionId: z6.string(),
|
|
1115
|
+
goal: z6.string(),
|
|
1116
|
+
kind: CourseKind,
|
|
1117
|
+
status: CourseStatus,
|
|
1118
|
+
syllabus: SyllabusView.nullable(),
|
|
1119
|
+
/** The tutor's reply that wrote the first syllabus, which ends the placement interview; null if unknown. */
|
|
1120
|
+
interviewMessageId: z6.string().nullable(),
|
|
1121
|
+
createdAt: z6.string().datetime()
|
|
1122
|
+
}).strict();
|
|
1123
|
+
|
|
1124
|
+
// ../protocol/src/graph.ts
|
|
1125
|
+
import { z as z7 } from "zod";
|
|
1126
|
+
var MAX_NODES = 60;
|
|
1127
|
+
var MAX_EDGES = 200;
|
|
1128
|
+
var MAX_STEPS2 = 200;
|
|
1129
|
+
var Id2 = z7.string().trim().min(1).max(24);
|
|
1130
|
+
var Text = z7.string().trim().min(1).max(24);
|
|
1131
|
+
var GraphTone = z7.enum(["active", "done", "muted"]);
|
|
1132
|
+
var ToneField = GraphTone.optional().describe(
|
|
1133
|
+
"active = current focus, done = finished/visited, muted = ruled out. Defaults to active."
|
|
1134
|
+
);
|
|
1135
|
+
var GraphNode = z7.object({
|
|
1136
|
+
id: Id2.describe("Unique id, used by edges and steps. Shown on the node if it has no label."),
|
|
1137
|
+
label: Text.optional().describe("Short text on the node. Only $...$ is a formula, e.g. $v_1$.")
|
|
1138
|
+
}).strict();
|
|
1139
|
+
var GraphEdge = z7.object({
|
|
1140
|
+
from: Id2.describe("Id of a node. In a tree, the parent."),
|
|
1141
|
+
to: Id2.describe("Id of a node, the same as `from` for a self-loop. In a tree, the child; children appear left to right in edge order unless they have a `side`."),
|
|
1142
|
+
side: z7.enum(["left", "right"]).optional().describe(
|
|
1143
|
+
"Only when kind is tree: which child this is of `from`, its parent. Set it on every edge of a binary search tree or binary tree traversal, because a lone left child and a lone right child are different trees. A node has at most one child per side, and either all of its children have a side or none do."
|
|
1144
|
+
),
|
|
1145
|
+
weight: z7.number().optional().describe("Numeric weight shown on the edge. Give a weight or a label, not both."),
|
|
1146
|
+
label: Text.optional().describe("Text shown on the edge. Only $...$ is a formula.")
|
|
1147
|
+
}).strict();
|
|
1148
|
+
var GraphNodeState = z7.object({ id: Id2.describe("Id of a node."), tone: ToneField }).strict();
|
|
1149
|
+
var GraphEdgeState = z7.object({
|
|
1150
|
+
from: Id2,
|
|
1151
|
+
to: Id2,
|
|
1152
|
+
nth: z7.number().int().nonnegative().optional().describe("Only for parallel edges, and then required: which of the edges joining these nodes, 0-based in the order of `edges`."),
|
|
1153
|
+
tone: ToneField
|
|
1154
|
+
}).strict().describe("An edge of the graph. In an undirected graph, from and to may be in either order.");
|
|
1155
|
+
var GraphStep = z7.object({
|
|
1156
|
+
explanation: z7.string().trim().min(1).max(500).describe("What happens in this step, in one or two sentences."),
|
|
1157
|
+
nodeStates: z7.array(GraphNodeState).max(MAX_NODES).optional().describe("The state of every node that has one at this step, at most one each. Not carried over from earlier steps: repeat any that still apply."),
|
|
1158
|
+
edgeStates: z7.array(GraphEdgeState).max(MAX_EDGES).optional().describe("The state of every edge that has one at this step, at most one each. Not carried over from earlier steps: repeat any that still apply."),
|
|
1159
|
+
variables: z7.array(TraceVariable).max(12).optional().describe("All running state at this step, e.g. the queue or current distances. Not carried over from earlier steps.")
|
|
1160
|
+
}).strict();
|
|
1161
|
+
var pairKey = (from, to, directed) => JSON.stringify(directed || from <= to ? [from, to] : [to, from]);
|
|
1162
|
+
function graphEdgeLookup(spec) {
|
|
1163
|
+
const byPair = /* @__PURE__ */ new Map();
|
|
1164
|
+
spec.edges.forEach((edge, i) => {
|
|
1165
|
+
const key = pairKey(edge.from, edge.to, spec.directed);
|
|
1166
|
+
const indices = byPair.get(key);
|
|
1167
|
+
if (indices) indices.push(i);
|
|
1168
|
+
else byPair.set(key, [i]);
|
|
1169
|
+
});
|
|
1170
|
+
return (ref) => {
|
|
1171
|
+
const name = `${ref.from} ${spec.directed ? "->" : "--"} ${ref.to}`;
|
|
1172
|
+
const indices = byPair.get(pairKey(ref.from, ref.to, spec.directed));
|
|
1173
|
+
if (!indices) return { error: `there is no edge ${name}` };
|
|
1174
|
+
if (ref.nth === void 0 && indices.length > 1) return { error: `${indices.length} edges match ${name}: set nth to pick one` };
|
|
1175
|
+
const index = indices[ref.nth ?? 0];
|
|
1176
|
+
return index === void 0 ? { error: `nth ${ref.nth} is out of range: ${indices.length} edges match ${name}` } : { index };
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
function graphTreeShape(spec) {
|
|
1180
|
+
if (spec.edges.length !== spec.nodes.length - 1) return void 0;
|
|
1181
|
+
const ids = spec.nodes.map((node) => node.id);
|
|
1182
|
+
const adjacent = new Map(ids.map((id) => [id, []]));
|
|
1183
|
+
for (const { from, to } of spec.edges) {
|
|
1184
|
+
adjacent.get(from).push(to);
|
|
1185
|
+
if (!spec.directed && from !== to) adjacent.get(to).push(from);
|
|
1186
|
+
}
|
|
1187
|
+
const roots = spec.directed ? ids.filter((id) => !spec.edges.some((edge) => edge.to === id)) : ids.slice(0, 1);
|
|
1188
|
+
const root = roots[0];
|
|
1189
|
+
if (roots.length !== 1 || root === void 0) return void 0;
|
|
1190
|
+
const children = /* @__PURE__ */ new Map();
|
|
1191
|
+
const pending = [root];
|
|
1192
|
+
while (pending.length) {
|
|
1193
|
+
const id = pending.pop();
|
|
1194
|
+
const next = adjacent.get(id).filter((other) => !children.has(other));
|
|
1195
|
+
children.set(id, next);
|
|
1196
|
+
pending.push(...next);
|
|
1197
|
+
}
|
|
1198
|
+
return children.size === ids.length ? { root, children } : void 0;
|
|
1199
|
+
}
|
|
1200
|
+
function checkSides(spec, ctx) {
|
|
1201
|
+
const sided = spec.edges.flatMap((edge, i) => edge.side ? [{ edge, side: edge.side, path: ["edges", i, "side"] }] : []);
|
|
1202
|
+
const first = sided[0];
|
|
1203
|
+
if (!first) return;
|
|
1204
|
+
if (spec.kind !== "tree") {
|
|
1205
|
+
for (const { path } of sided) ctx.addIssue({ code: "custom", path, message: 'side only applies when kind is "tree": remove it, or set kind' });
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
const shape = graphTreeShape(spec);
|
|
1209
|
+
if (!shape) {
|
|
1210
|
+
ctx.addIssue({ code: "custom", path: first.path, message: "side needs a real tree: connected with no cycles, and when directed, edges going parent to child from one root" });
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
const sideOf = /* @__PURE__ */ new Map();
|
|
1214
|
+
for (const { edge, side, path } of sided) {
|
|
1215
|
+
if (shape.children.get(edge.from).includes(edge.to)) sideOf.set(edge.to, side);
|
|
1216
|
+
else ctx.addIssue({ code: "custom", path, message: `side needs from to be the parent, but ${edge.to} is the parent of ${edge.from} here: swap them` });
|
|
1217
|
+
}
|
|
1218
|
+
for (const [parent, children] of shape.children) {
|
|
1219
|
+
const sides = children.flatMap((child) => sideOf.get(child) ?? []);
|
|
1220
|
+
if (sides.length > 0 && sides.length < children.length) {
|
|
1221
|
+
ctx.addIssue({ code: "custom", path: ["edges"], message: `node ${parent} mixes children with and without a side: give all of them one, or none` });
|
|
1222
|
+
}
|
|
1223
|
+
for (const side of ["left", "right"]) {
|
|
1224
|
+
if (sides.filter((s) => s === side).length > 1) ctx.addIssue({ code: "custom", path: ["edges"], message: `node ${parent} has two ${side} children` });
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
var GraphSpec = z7.object({
|
|
1229
|
+
title: z7.string().trim().min(1).max(120),
|
|
1230
|
+
directed: z7.boolean().describe("True draws arrowheads from `from` to `to`."),
|
|
1231
|
+
kind: z7.enum(["tree", "graph"]).optional().describe(
|
|
1232
|
+
"Layout hint. tree draws a rooted tree top-down, and needs a real tree: connected with no cycles, and when directed, edges going parent to child from one root. When undirected, the first node is the root. Anything else falls back to the general layout, unless an edge has a `side`, which is then an error. Defaults to graph."
|
|
1233
|
+
),
|
|
1234
|
+
nodes: z7.array(GraphNode).min(1).max(MAX_NODES),
|
|
1235
|
+
edges: z7.array(GraphEdge).max(MAX_EDGES).describe("Self-loops and parallel edges are allowed."),
|
|
1236
|
+
steps: z7.array(GraphStep).min(1).max(MAX_STEPS2).optional().describe("Omit to show the graph without stepping through it.")
|
|
1237
|
+
}).strict().superRefine((spec, ctx) => {
|
|
1238
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1239
|
+
spec.nodes.forEach((node, i) => {
|
|
1240
|
+
if (ids.has(node.id)) ctx.addIssue({ code: "custom", path: ["nodes", i, "id"], message: `duplicate node id ${node.id}` });
|
|
1241
|
+
ids.add(node.id);
|
|
1242
|
+
});
|
|
1243
|
+
spec.edges.forEach((edge, i) => {
|
|
1244
|
+
for (const end of ["from", "to"]) {
|
|
1245
|
+
if (!ids.has(edge[end])) ctx.addIssue({ code: "custom", path: ["edges", i, end], message: `no node has id ${edge[end]}` });
|
|
1246
|
+
}
|
|
1247
|
+
if (edge.weight !== void 0 && edge.label !== void 0) {
|
|
1248
|
+
ctx.addIssue({ code: "custom", path: ["edges", i], message: "give a weight or a label, not both" });
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
if (spec.edges.every((edge) => ids.has(edge.from) && ids.has(edge.to))) checkSides(spec, ctx);
|
|
1252
|
+
const lookup = graphEdgeLookup(spec);
|
|
1253
|
+
spec.steps?.forEach((step, i) => {
|
|
1254
|
+
const seenNodes = /* @__PURE__ */ new Set();
|
|
1255
|
+
step.nodeStates?.forEach((state, j) => {
|
|
1256
|
+
const path = ["steps", i, "nodeStates", j];
|
|
1257
|
+
if (!ids.has(state.id)) ctx.addIssue({ code: "custom", path, message: `no node has id ${state.id}` });
|
|
1258
|
+
if (seenNodes.has(state.id)) ctx.addIssue({ code: "custom", path, message: `node ${state.id} has two states in one step` });
|
|
1259
|
+
seenNodes.add(state.id);
|
|
1260
|
+
});
|
|
1261
|
+
const seenEdges = /* @__PURE__ */ new Set();
|
|
1262
|
+
step.edgeStates?.forEach((state, j) => {
|
|
1263
|
+
const path = ["steps", i, "edgeStates", j];
|
|
1264
|
+
const found = lookup(state);
|
|
1265
|
+
if ("error" in found) return ctx.addIssue({ code: "custom", path, message: found.error });
|
|
1266
|
+
if (seenEdges.has(found.index)) ctx.addIssue({ code: "custom", path, message: `edge ${found.index} has two states in one step` });
|
|
1267
|
+
seenEdges.add(found.index);
|
|
1268
|
+
});
|
|
1269
|
+
});
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1272
|
+
// ../protocol/src/multiple-choice.ts
|
|
1273
|
+
import { z as z8 } from "zod";
|
|
1274
|
+
var MultipleChoiceOption = z8.object({
|
|
1275
|
+
text: z8.string().trim().min(1).max(300),
|
|
1276
|
+
feedback: z8.string().trim().min(1).max(500).optional().describe("Shown if the learner picks this option: why it is right or what misconception it reflects.")
|
|
1277
|
+
}).strict();
|
|
1278
|
+
var MultipleChoiceSpec = z8.object({
|
|
1279
|
+
concept: z8.string().trim().min(1).max(80).describe('Short label for the concept being checked, e.g. "sliding window invariant". Used to track progress.'),
|
|
1280
|
+
question: z8.string().trim().min(1).max(1e3),
|
|
1281
|
+
options: z8.array(MultipleChoiceOption).min(2).max(6).describe("2-6 options with distinct text."),
|
|
1282
|
+
correctOptionIndex: z8.number().int().nonnegative().describe("0-based index of the single correct option; must be less than the number of options."),
|
|
1283
|
+
explanation: z8.string().trim().min(1).max(1e3).describe("Shown after answering: why the correct option is correct.")
|
|
1284
|
+
}).strict().superRefine((spec, ctx) => {
|
|
1285
|
+
if (spec.correctOptionIndex >= spec.options.length) {
|
|
1286
|
+
ctx.addIssue({
|
|
1287
|
+
code: "custom",
|
|
1288
|
+
path: ["correctOptionIndex"],
|
|
1289
|
+
message: "correctOptionIndex must point at one of the options"
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1293
|
+
spec.options.forEach((option, i) => {
|
|
1294
|
+
const key = option.text.normalize("NFC");
|
|
1295
|
+
const first = seen.get(key);
|
|
1296
|
+
if (first !== void 0) {
|
|
1297
|
+
ctx.addIssue({ code: "custom", path: ["options", i, "text"], message: `duplicates option ${first}` });
|
|
1298
|
+
} else {
|
|
1299
|
+
seen.set(key, i);
|
|
1300
|
+
}
|
|
1301
|
+
});
|
|
1302
|
+
});
|
|
1303
|
+
var MultipleChoicePublic = z8.object({
|
|
1304
|
+
concept: z8.string(),
|
|
1305
|
+
question: z8.string(),
|
|
1306
|
+
options: z8.array(z8.object({ text: z8.string() }).strict())
|
|
1307
|
+
}).strict();
|
|
1308
|
+
function toMultipleChoicePublic(spec) {
|
|
1309
|
+
return {
|
|
1310
|
+
concept: spec.concept,
|
|
1311
|
+
question: spec.question,
|
|
1312
|
+
options: spec.options.map((o) => ({ text: o.text }))
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
var MultipleChoiceAnswer = z8.object({ optionIndex: z8.number().int().nonnegative() }).strict();
|
|
1316
|
+
var MultipleChoiceGrade = z8.object({
|
|
1317
|
+
correct: z8.boolean(),
|
|
1318
|
+
correctOptionIndex: z8.number().int().nonnegative(),
|
|
1319
|
+
explanation: z8.string(),
|
|
1320
|
+
feedback: z8.string().optional()
|
|
1321
|
+
}).strict();
|
|
1322
|
+
function gradeMultipleChoice(spec, answer) {
|
|
1323
|
+
const chosen = spec.options[answer.optionIndex];
|
|
1324
|
+
if (!chosen) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);
|
|
1325
|
+
return {
|
|
1326
|
+
correct: answer.optionIndex === spec.correctOptionIndex,
|
|
1327
|
+
correctOptionIndex: spec.correctOptionIndex,
|
|
1328
|
+
explanation: spec.explanation,
|
|
1329
|
+
...chosen.feedback ? { feedback: chosen.feedback } : {}
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// ../protocol/src/project-milestone.ts
|
|
1334
|
+
import { z as z9 } from "zod";
|
|
1335
|
+
var MILESTONE_CHECK_TYPES = ["tests", "review"];
|
|
1336
|
+
var MilestoneCheckType = z9.enum(MILESTONE_CHECK_TYPES);
|
|
1337
|
+
var MilestoneCompare = z9.enum(["stdout", "run_output"]);
|
|
1338
|
+
var MAX_MILESTONE_REFERENCE_CHARS = 2e4;
|
|
1339
|
+
var MAX_MILESTONE_STDERR_CHARS = 2e3;
|
|
1340
|
+
var MAX_REVIEW_FILES = 200;
|
|
1341
|
+
var MAX_REVIEW_FILE_CHARS = 6e4;
|
|
1342
|
+
var MAX_REVIEW_TOTAL_CHARS = 24e4;
|
|
1343
|
+
var MAX_REVIEW_PATH_CHARS = 500;
|
|
1344
|
+
var CommitId = z9.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/);
|
|
1345
|
+
var MilestoneCaseInput = z9.object({
|
|
1346
|
+
name: z9.string().trim().min(1).max(80).describe('A short name the learner sees, e.g. "empty input" or "nested parentheses".'),
|
|
1347
|
+
input: z9.string().max(MAX_CASE_INPUT_CHARS).describe(`The case's input. The learner's program gets it on stdin and as a file whose path replaces {input} in their command. Use "" for none.`),
|
|
1348
|
+
compare: MilestoneCompare.optional().describe(
|
|
1349
|
+
"stdout (the default) compares what the learner's program prints. run_output is for programs whose output is itself a program, such as a compiler's generated assembly: Mivra runs that output with the learner's own run-output command and compares what it prints, so the reference prints what running it should print."
|
|
1350
|
+
)
|
|
1351
|
+
}).strict();
|
|
1352
|
+
var milestoneFields = {
|
|
1353
|
+
concept: z9.string().trim().min(1).max(80).describe('Short label for what this milestone practises, e.g. "tokenizing". Used to track progress.'),
|
|
1354
|
+
title: z9.string().trim().min(1).max(120),
|
|
1355
|
+
spec: z9.string().trim().min(1).max(6e3).describe("What the learner's program must do at this milestone, as markdown: the behaviour to add, building on the earlier milestones."),
|
|
1356
|
+
outputFormat: z9.string().trim().min(1).max(2e3).describe("Exactly what the program prints for an input, as markdown with an example, so any language can match it. Trailing spaces and trailing blank lines are ignored."),
|
|
1357
|
+
checkType: MilestoneCheckType.describe(
|
|
1358
|
+
"tests: Mivra runs the learner's program on the cases and compares what it prints, and a code review must approve too. review: no cases or reference; the code review alone decides, for what output can't show (structure, a language feature, concurrency, performance)."
|
|
1359
|
+
),
|
|
1360
|
+
reviewFocus: z9.string().trim().min(1).max(2e3).optional().describe(
|
|
1361
|
+
`What the code review must see in the learner's code for this milestone's concept, e.g. "the scanner walks the characters itself rather than splitting with a regex". Required for a review milestone; optional for tests.`
|
|
1362
|
+
)
|
|
1363
|
+
};
|
|
1364
|
+
function milestoneRules(value, ctx) {
|
|
1365
|
+
if (value.checkType === "tests") {
|
|
1366
|
+
if (!value.cases || value.cases.length === 0) ctx.addIssue({ code: "custom", path: ["cases"], message: "A tests milestone needs at least one case." });
|
|
1367
|
+
if (!value.referenceSolution) ctx.addIssue({ code: "custom", path: ["referenceSolution"], message: "A tests milestone needs a referenceSolution." });
|
|
1368
|
+
} else {
|
|
1369
|
+
if (value.cases && value.cases.length > 0) ctx.addIssue({ code: "custom", path: ["cases"], message: "A review milestone has no cases: the code review decides. Leave cases out." });
|
|
1370
|
+
if (value.referenceSolution) ctx.addIssue({ code: "custom", path: ["referenceSolution"], message: "A review milestone has no reference. Leave referenceSolution out." });
|
|
1371
|
+
if (!value.reviewFocus) ctx.addIssue({ code: "custom", path: ["reviewFocus"], message: "A review milestone needs reviewFocus: what the review must see in the code." });
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
var ProjectMilestoneInput = z9.object({
|
|
1375
|
+
...milestoneFields,
|
|
1376
|
+
cases: z9.array(MilestoneCaseInput).max(MAX_EXERCISE_CASES).optional().describe(`tests only: 1-${MAX_EXERCISE_CASES} cases, simplest first, covering the milestone's edge cases. Each reference run has a 2 s limit. Leave out for review.`),
|
|
1377
|
+
referenceSolution: z9.string().min(1).max(MAX_MILESTONE_REFERENCE_CHARS).optional().describe(
|
|
1378
|
+
"tests only: a Python program (standard library only) that reads a case's input from stdin and prints exactly what the learner's program should print, or for a run_output case what running its output should print. Mivra runs it in Pyodide on every case to get the expected outputs and never shows it. It must be deterministic. Leave out for review."
|
|
1379
|
+
)
|
|
1380
|
+
}).strict().superRefine(milestoneRules);
|
|
1381
|
+
var MilestoneCase = MilestoneCaseInput.extend({
|
|
1382
|
+
expected: z9.string().max(MAX_CASE_OUTPUT_CHARS),
|
|
1383
|
+
/** Withdrawn by the tutor after a dispute: kept for the record, never run or graded again. */
|
|
1384
|
+
withdrawn: z9.boolean().optional()
|
|
1385
|
+
}).strict();
|
|
1386
|
+
var MAX_MILESTONE_DISPUTES = 20;
|
|
1387
|
+
var MAX_DISPUTE_REASON_CHARS = 2e3;
|
|
1388
|
+
var MilestoneDisputeOutcome = z9.enum(["kept", "withdrawn", "corrected", "upheld", "overturned"]);
|
|
1389
|
+
var MilestoneDispute = z9.object({
|
|
1390
|
+
id: z9.string(),
|
|
1391
|
+
target: z9.enum(["case", "review"]),
|
|
1392
|
+
/** The disputed case's index in `cases`, and its name then. */
|
|
1393
|
+
caseIndex: z9.number().int().nonnegative().optional(),
|
|
1394
|
+
caseName: z9.string().optional(),
|
|
1395
|
+
reason: z9.string().max(MAX_DISPUTE_REASON_CHARS),
|
|
1396
|
+
outcome: MilestoneDisputeOutcome,
|
|
1397
|
+
/** The tutor's explanation, for the learner. */
|
|
1398
|
+
explanation: z9.string().max(2e3),
|
|
1399
|
+
/** A corrected case as it was before. */
|
|
1400
|
+
before: z9.object({ input: z9.string(), expected: z9.string() }).strict().optional(),
|
|
1401
|
+
createdAt: z9.string().datetime()
|
|
1402
|
+
}).strict();
|
|
1403
|
+
var ProjectMilestoneSpec = z9.object({
|
|
1404
|
+
...milestoneFields,
|
|
1405
|
+
cases: z9.array(MilestoneCase).max(MAX_EXERCISE_CASES),
|
|
1406
|
+
referenceSolution: z9.string().max(MAX_MILESTONE_REFERENCE_CHARS).optional(),
|
|
1407
|
+
disputes: z9.array(MilestoneDispute).max(MAX_MILESTONE_DISPUTES).optional()
|
|
1408
|
+
}).strict();
|
|
1409
|
+
var activeMilestoneCases = (spec) => spec.cases.flatMap((testCase, index) => testCase.withdrawn ? [] : [{ ...testCase, index }]);
|
|
1410
|
+
var ProjectMilestonePublic = z9.object({
|
|
1411
|
+
concept: z9.string(),
|
|
1412
|
+
title: z9.string(),
|
|
1413
|
+
spec: z9.string(),
|
|
1414
|
+
outputFormat: z9.string(),
|
|
1415
|
+
checkType: MilestoneCheckType,
|
|
1416
|
+
reviewFocus: z9.string().optional(),
|
|
1417
|
+
cases: z9.array(z9.object({ name: z9.string(), input: z9.string(), compare: MilestoneCompare, expected: z9.string(), withdrawn: z9.boolean().optional() }).strict()),
|
|
1418
|
+
disputes: z9.array(MilestoneDispute)
|
|
1419
|
+
}).strict();
|
|
1420
|
+
var toProjectMilestonePublic = (spec) => ({
|
|
1421
|
+
concept: spec.concept,
|
|
1422
|
+
title: spec.title,
|
|
1423
|
+
spec: spec.spec,
|
|
1424
|
+
outputFormat: spec.outputFormat,
|
|
1425
|
+
checkType: spec.checkType,
|
|
1426
|
+
...spec.reviewFocus ? { reviewFocus: spec.reviewFocus } : {},
|
|
1427
|
+
cases: spec.cases.map((c) => ({ name: c.name, input: c.input, compare: c.compare ?? "stdout", expected: c.expected, ...c.withdrawn ? { withdrawn: true } : {} })),
|
|
1428
|
+
disputes: spec.disputes ?? []
|
|
1429
|
+
});
|
|
1430
|
+
var MilestoneCases = z9.object({
|
|
1431
|
+
courseId: z9.string(),
|
|
1432
|
+
lessonId: z9.string(),
|
|
1433
|
+
artifactId: z9.string(),
|
|
1434
|
+
/** The milestone's place in the syllabus, from 1. */
|
|
1435
|
+
position: z9.number().int().positive(),
|
|
1436
|
+
title: z9.string(),
|
|
1437
|
+
checkType: MilestoneCheckType,
|
|
1438
|
+
/** Names this set of cases; a check reports it back, so results for cases a dispute changed meanwhile are refused. */
|
|
1439
|
+
revision: z9.string().regex(/^[0-9a-f]{8,64}$/),
|
|
1440
|
+
/**
|
|
1441
|
+
* The commit the last passed milestone was checked at, if any: `mivra check` sends only what changed since. Only a
|
|
1442
|
+
* commit id, which `mivra check` hands to git as data.
|
|
1443
|
+
*/
|
|
1444
|
+
since: CommitId.nullable(),
|
|
1445
|
+
/** The cases to run; withdrawn ones are left out. A review milestone has none. */
|
|
1446
|
+
cases: z9.array(z9.object({ name: z9.string(), input: z9.string().max(MAX_CASE_INPUT_CHARS), compare: MilestoneCompare }).strict()).max(MAX_EXERCISE_CASES)
|
|
1447
|
+
}).strict();
|
|
1448
|
+
var MilestoneRunError = z9.enum(["timeout", "output_limit", "start_failed", "no_run_output_command"]);
|
|
1449
|
+
var MilestoneCaseResult = z9.object({
|
|
1450
|
+
stdout: z9.string().max(MAX_CASE_OUTPUT_CHARS),
|
|
1451
|
+
truncated: z9.boolean().optional(),
|
|
1452
|
+
stderr: z9.string().max(MAX_MILESTONE_STDERR_CHARS).optional(),
|
|
1453
|
+
/** The exit code, or null if it was killed or never started. */
|
|
1454
|
+
exitCode: z9.number().int().nullable(),
|
|
1455
|
+
error: MilestoneRunError.optional()
|
|
1456
|
+
}).strict();
|
|
1457
|
+
var ReviewFile = z9.object({ path: z9.string().min(1).max(MAX_REVIEW_PATH_CHARS), content: z9.string().max(MAX_REVIEW_FILE_CHARS) }).strict();
|
|
1458
|
+
var ReviewSkipReason = z9.enum(["binary", "too_large", "size_cap", "lockfile"]);
|
|
1459
|
+
var reviewFields = {
|
|
1460
|
+
/** The commit checked out when the check ran (the files may have changed since), if the repository has one. */
|
|
1461
|
+
commit: CommitId.optional(),
|
|
1462
|
+
/** Where the files came from: git, or nowhere outside a git repository (nothing is sent then). */
|
|
1463
|
+
source: z9.enum(["git", "none"]).optional(),
|
|
1464
|
+
files: z9.array(ReviewFile).max(MAX_REVIEW_FILES).optional(),
|
|
1465
|
+
/** Paths of changed files that weren't sent, and why. */
|
|
1466
|
+
skipped: z9.array(z9.object({ path: z9.string().max(MAX_REVIEW_PATH_CHARS), reason: ReviewSkipReason }).strict()).max(1e3).optional(),
|
|
1467
|
+
/** Paths deleted since the last passed milestone. */
|
|
1468
|
+
deleted: z9.array(z9.string().max(MAX_REVIEW_PATH_CHARS)).max(1e3).optional()
|
|
1469
|
+
};
|
|
1470
|
+
var MilestoneCheckAnswer = z9.object({
|
|
1471
|
+
results: z9.array(MilestoneCaseResult).max(MAX_EXERCISE_CASES),
|
|
1472
|
+
/** The `revision` of the cases that ran. Left out by a `mivra check` from before disputes. */
|
|
1473
|
+
revision: z9.string().max(64).optional(),
|
|
1474
|
+
...reviewFields
|
|
1475
|
+
}).strict().superRefine((answer, ctx) => {
|
|
1476
|
+
const total = (answer.files ?? []).reduce((sum, file) => sum + file.content.length, 0);
|
|
1477
|
+
if (total > MAX_REVIEW_TOTAL_CHARS) ctx.addIssue({ code: "custom", path: ["files"], message: `At most ${MAX_REVIEW_TOTAL_CHARS} characters of files can be sent.` });
|
|
1478
|
+
});
|
|
1479
|
+
var MilestoneGrade = z9.object({
|
|
1480
|
+
/** Every case that ran passed (true when there were none to run). Not the milestone's pass: that needs the review too. */
|
|
1481
|
+
correct: z9.boolean(),
|
|
1482
|
+
passed: z9.number().int().nonnegative(),
|
|
1483
|
+
total: z9.number().int().nonnegative(),
|
|
1484
|
+
/** One per case that ran, with its index in the spec's `cases` (missing in grades from before disputes: then in order). */
|
|
1485
|
+
cases: z9.array(z9.object({ passed: z9.boolean(), case: z9.number().int().nonnegative().optional() }).strict())
|
|
1486
|
+
}).strict();
|
|
1487
|
+
function milestoneCasePassed(expected, run) {
|
|
1488
|
+
return run.error === void 0 && !run.truncated && run.exitCode === 0 && normaliseOutput(run.stdout) === normaliseOutput(expected);
|
|
1489
|
+
}
|
|
1490
|
+
function gradeMilestone(spec, answer) {
|
|
1491
|
+
const active = activeMilestoneCases(spec);
|
|
1492
|
+
if (answer.results.length !== active.length) {
|
|
1493
|
+
throw new RangeError(`Expected results for ${active.length} cases, got ${answer.results.length}`);
|
|
1494
|
+
}
|
|
1495
|
+
const cases = active.map((c, i) => ({ passed: milestoneCasePassed(c.expected, answer.results[i]), case: c.index }));
|
|
1496
|
+
const passed = cases.filter((c) => c.passed).length;
|
|
1497
|
+
return { correct: passed === cases.length, passed, total: cases.length, cases };
|
|
1498
|
+
}
|
|
1499
|
+
var ReviewCriterion = z9.object({
|
|
1500
|
+
passed: z9.boolean(),
|
|
1501
|
+
note: z9.string().trim().min(1).max(1e3).describe("One to three sentences for the learner, pointing at the file and the code you mean.")
|
|
1502
|
+
}).strict();
|
|
1503
|
+
var MilestoneReviewInput = z9.object({
|
|
1504
|
+
noHardCodedOutputs: ReviewCriterion.describe(
|
|
1505
|
+
"passed is false if the program special-cases test inputs or prints canned answers instead of computing them, e.g. matching an input string and printing its expected output."
|
|
1506
|
+
),
|
|
1507
|
+
concept: ReviewCriterion.describe("passed is true if the code really does what this milestone teaches (its concept and reviewFocus), not just something that produces the same output."),
|
|
1508
|
+
quality: ReviewCriterion.describe(
|
|
1509
|
+
"passed is false only for serious problems for a learner at this stage: code that can't be followed, copy-pasted blocks instead of a loop or function, or obvious bugs the tests miss. Style preferences never fail it."
|
|
1510
|
+
),
|
|
1511
|
+
summary: z9.string().trim().min(1).max(1500).describe("What you'd tell the learner: what's good, and what to change if anything."),
|
|
1512
|
+
suggestions: z9.array(z9.string().trim().min(1).max(500)).max(8).describe("Optional next steps, most useful first. Never write the solution.")
|
|
1513
|
+
}).strict();
|
|
1514
|
+
var MilestoneReview = MilestoneReviewInput.extend({
|
|
1515
|
+
approved: z9.boolean(),
|
|
1516
|
+
judgedBy: z9.literal("model"),
|
|
1517
|
+
/** The model that reviewed, as shown in the picker. */
|
|
1518
|
+
model: z9.string()
|
|
1519
|
+
}).strict();
|
|
1520
|
+
var reviewVerdict = (input, model) => ({
|
|
1521
|
+
...input,
|
|
1522
|
+
approved: input.noHardCodedOutputs.passed && input.concept.passed && input.quality.passed,
|
|
1523
|
+
judgedBy: "model",
|
|
1524
|
+
model
|
|
1525
|
+
});
|
|
1526
|
+
var MilestoneReviewStatus = z9.discriminatedUnion("status", [
|
|
1527
|
+
z9.object({ status: z9.literal("done"), review: MilestoneReview }).strict(),
|
|
1528
|
+
z9.object({ status: z9.literal("skipped"), reason: z9.enum(["tests_failed", "no_files"]) }).strict(),
|
|
1529
|
+
z9.object({ status: z9.literal("failed"), error: z9.string() }).strict()
|
|
1530
|
+
]);
|
|
1531
|
+
var milestonePassed = (grade, review) => grade.correct && review?.approved === true;
|
|
1532
|
+
var MilestoneCheckResult = z9.object({
|
|
1533
|
+
grade: MilestoneGrade,
|
|
1534
|
+
expected: z9.array(z9.string()),
|
|
1535
|
+
review: MilestoneReviewStatus,
|
|
1536
|
+
passed: z9.boolean()
|
|
1537
|
+
}).strict();
|
|
1538
|
+
var MilestoneDisputeRequest = z9.discriminatedUnion("target", [
|
|
1539
|
+
z9.object({ target: z9.literal("case"), caseIndex: z9.number().int().nonnegative().max(MAX_EXERCISE_CASES - 1), reason: z9.string().trim().min(1).max(MAX_DISPUTE_REASON_CHARS) }).strict(),
|
|
1540
|
+
z9.object({ target: z9.literal("review"), reason: z9.string().trim().min(1).max(MAX_DISPUTE_REASON_CHARS) }).strict()
|
|
1541
|
+
]);
|
|
1542
|
+
var CaseDisputeDecision = z9.object({
|
|
1543
|
+
outcome: z9.enum(["keep", "withdraw", "correct"]).describe("keep: the case is right. withdraw: it's wrong or unfair and can't simply be fixed. correct: fix its input or the reference."),
|
|
1544
|
+
explanation: z9.string().trim().min(1).max(2e3).describe("For the learner: why, in two or three sentences."),
|
|
1545
|
+
input: z9.string().max(MAX_CASE_INPUT_CHARS).optional().describe("correct only: the case's corrected input, if the input was wrong."),
|
|
1546
|
+
referenceSolution: z9.string().min(1).max(MAX_MILESTONE_REFERENCE_CHARS).optional().describe("correct only: the whole corrected Python reference, if its output was wrong. Mivra reruns it on every case.")
|
|
1547
|
+
}).strict();
|
|
1548
|
+
var MilestoneCheckView = z9.object({
|
|
1549
|
+
results: z9.array(MilestoneCaseResult),
|
|
1550
|
+
files: z9.array(z9.string()),
|
|
1551
|
+
skipped: z9.array(z9.object({ path: z9.string(), reason: ReviewSkipReason }).strict()).optional(),
|
|
1552
|
+
source: z9.enum(["git", "none"]).optional()
|
|
1553
|
+
}).strict();
|
|
1554
|
+
var toMilestoneCheckView = (answer) => ({
|
|
1555
|
+
results: answer.results,
|
|
1556
|
+
files: (answer.files ?? []).map((f) => f.path),
|
|
1557
|
+
...answer.skipped?.length ? { skipped: answer.skipped } : {},
|
|
1558
|
+
...answer.source ? { source: answer.source } : {}
|
|
1559
|
+
});
|
|
1560
|
+
|
|
1561
|
+
// ../protocol/src/set-diagram.ts
|
|
1562
|
+
import { z as z10 } from "zod";
|
|
1563
|
+
var MAX_SETS = 3;
|
|
1564
|
+
var MAX_REGIONS = 8;
|
|
1565
|
+
var MAX_ELEMENTS = 30;
|
|
1566
|
+
var MAX_STEPS3 = 40;
|
|
1567
|
+
var SetId = z10.string().trim().min(1).max(24);
|
|
1568
|
+
var ONE_LINE = /^[^\n\r\v\f\u0085\u2028\u2029]*$/;
|
|
1569
|
+
var oneLine = (max) => z10.string().trim().min(1).max(max).regex(ONE_LINE, "must not contain line breaks");
|
|
1570
|
+
var Element = z10.union([z10.number(), oneLine(24)]);
|
|
1571
|
+
function setRegionKey(ids) {
|
|
1572
|
+
return JSON.stringify([...ids].sort());
|
|
1573
|
+
}
|
|
1574
|
+
var RegionIn = z10.array(SetId).max(MAX_SETS);
|
|
1575
|
+
var SetDiagramSet = z10.object({
|
|
1576
|
+
id: SetId.describe('Short id used to refer to this set, e.g. "a". Unique within the diagram.'),
|
|
1577
|
+
label: oneLine(32).describe('Shown next to the circle, e.g. "$A$" or "Multiples of 3", on one line. Only $...$ is a formula.')
|
|
1578
|
+
}).strict();
|
|
1579
|
+
var SetDiagramRegion = z10.object({
|
|
1580
|
+
in: RegionIn.describe('Ids of the sets this region is inside. It is outside all the others: with sets a, b, c, ["a","b"] means in a and b, not c. [] means outside every set and needs `universe`. No id twice.'),
|
|
1581
|
+
elements: z10.array(Element).max(MAX_ELEMENTS).describe('What the region contains, each short and on one line. No element may appear twice, in this list or across regions, and 1 and "1" count as the same element. Empty if you only know the count, or the region is empty.'),
|
|
1582
|
+
count: z10.number().int().nonnegative().max(1e6).optional().describe("How many elements the region has, when that's more than you list, e.g. for inclusion-exclusion. At least the number of elements listed.")
|
|
1583
|
+
}).strict();
|
|
1584
|
+
var SetDiagramHighlight = z10.object({
|
|
1585
|
+
in: RegionIn.describe("The region to highlight, named like a region's `in`, with no id twice. Any region of the diagram can be highlighted, listed or not."),
|
|
1586
|
+
tone: z10.enum(["active", "done", "muted"]).optional().describe("active = current focus, done = finished, muted = ruled out. Defaults to active.")
|
|
1587
|
+
}).strict();
|
|
1588
|
+
var SetDiagramStep = z10.object({
|
|
1589
|
+
explanation: z10.string().trim().min(1).max(500).describe("What this step shows, in one or two sentences."),
|
|
1590
|
+
highlights: z10.array(SetDiagramHighlight).max(MAX_REGIONS).optional().describe("All regions highlighted at this step, each at most once. They apply to this step only, not carried over: repeat any that still apply."),
|
|
1591
|
+
variables: z10.array(TraceVariable).max(12).optional().describe("All running state at this step, e.g. |A \u222A B| so far. Not carried over from earlier steps.")
|
|
1592
|
+
}).strict();
|
|
1593
|
+
var SetDiagramSpec = z10.object({
|
|
1594
|
+
title: z10.string().trim().min(1).max(120),
|
|
1595
|
+
sets: z10.array(SetDiagramSet).min(1).max(MAX_SETS).describe("The circles, 1 to 3."),
|
|
1596
|
+
universe: oneLine(24).optional().describe('Label of the rectangle around the sets, e.g. "$U$", on one line. Needed to show or highlight the region outside every set, such as a complement.'),
|
|
1597
|
+
regions: z10.array(SetDiagramRegion).max(MAX_REGIONS).describe("What each region contains, each region at most once."),
|
|
1598
|
+
steps: z10.array(SetDiagramStep).min(1).max(MAX_STEPS3).optional().describe("Optional walk through the diagram. Omit for a static diagram.")
|
|
1599
|
+
}).strict().superRefine((spec, ctx) => {
|
|
1600
|
+
const ids = spec.sets.map((s) => s.id);
|
|
1601
|
+
spec.sets.forEach((set, i) => {
|
|
1602
|
+
if (ids.indexOf(set.id) !== i) ctx.addIssue({ code: "custom", path: ["sets", i, "id"], message: `duplicate set id "${set.id}"` });
|
|
1603
|
+
});
|
|
1604
|
+
const checkRegions = (entries, path) => {
|
|
1605
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1606
|
+
entries.forEach((entry, i) => {
|
|
1607
|
+
const at = [...path, i, "in"];
|
|
1608
|
+
entry.in.forEach((id, j) => {
|
|
1609
|
+
if (!ids.includes(id)) ctx.addIssue({ code: "custom", path: [...at, j], message: `unknown set "${id}"` });
|
|
1610
|
+
if (entry.in.indexOf(id) !== j) ctx.addIssue({ code: "custom", path: [...at, j], message: `set "${id}" is named twice` });
|
|
1611
|
+
});
|
|
1612
|
+
if (entry.in.length === 0 && spec.universe === void 0) {
|
|
1613
|
+
ctx.addIssue({ code: "custom", path: at, message: "the region outside every set needs `universe`" });
|
|
1614
|
+
}
|
|
1615
|
+
const key = setRegionKey(entry.in);
|
|
1616
|
+
if (seen.has(key)) ctx.addIssue({ code: "custom", path: at, message: `region ${key} appears more than once` });
|
|
1617
|
+
seen.add(key);
|
|
1618
|
+
});
|
|
1619
|
+
};
|
|
1620
|
+
checkRegions(spec.regions, ["regions"]);
|
|
1621
|
+
spec.steps?.forEach((step, i) => checkRegions(step.highlights ?? [], ["steps", i, "highlights"]));
|
|
1622
|
+
const placed = /* @__PURE__ */ new Set();
|
|
1623
|
+
spec.regions.forEach((region, i) => {
|
|
1624
|
+
region.elements.forEach((element, j) => {
|
|
1625
|
+
if (placed.has(String(element))) {
|
|
1626
|
+
ctx.addIssue({ code: "custom", path: ["regions", i, "elements", j], message: `element "${element}" appears more than once; regions don't overlap` });
|
|
1627
|
+
}
|
|
1628
|
+
placed.add(String(element));
|
|
1629
|
+
});
|
|
1630
|
+
if (region.count !== void 0 && region.count < region.elements.length) {
|
|
1631
|
+
ctx.addIssue({ code: "custom", path: ["regions", i, "count"], message: `count ${region.count} is less than the ${region.elements.length} elements listed` });
|
|
1632
|
+
}
|
|
1633
|
+
});
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
// ../protocol/src/table.ts
|
|
1637
|
+
import { z as z11 } from "zod";
|
|
1638
|
+
var MAX_COLUMNS = 16;
|
|
1639
|
+
var MAX_ROWS = 64;
|
|
1640
|
+
var MAX_STEPS4 = 100;
|
|
1641
|
+
var Header = z11.string().trim().min(1).max(80);
|
|
1642
|
+
var CellValue = z11.union([z11.number(), z11.boolean(), z11.string().max(120)]);
|
|
1643
|
+
var Index2 = z11.number().int().nonnegative();
|
|
1644
|
+
var TableHighlight = z11.object({
|
|
1645
|
+
row: Index2.optional().describe("0-based data row, below the number of rows. With no column, highlights the whole row. A highlight must give a row, a column or both."),
|
|
1646
|
+
column: Index2.optional().describe("0-based data column, below the number of columns. With no row, highlights the whole column. With both, highlights one cell."),
|
|
1647
|
+
tone: z11.enum(["active", "done", "muted"]).optional().describe("active = current focus, done = finished, muted = ruled out. Defaults to active. Where highlights overlap, the later one wins.")
|
|
1648
|
+
}).strict();
|
|
1649
|
+
var TableCellChange = z11.object({
|
|
1650
|
+
row: Index2.describe("0-based data row, below the number of rows."),
|
|
1651
|
+
column: Index2.describe("0-based data column, below the number of columns."),
|
|
1652
|
+
value: CellValue.describe("The cell's value from this step on.")
|
|
1653
|
+
}).strict();
|
|
1654
|
+
var TableStep = z11.object({
|
|
1655
|
+
explanation: z11.string().trim().min(1).max(500).describe("What happens in this step, in one or two sentences."),
|
|
1656
|
+
highlight: z11.array(TableHighlight).max(32).optional().describe("All cells, rows and columns to highlight at this step. Not carried over from earlier steps."),
|
|
1657
|
+
cells: z11.array(TableCellChange).max(64).optional().describe('Cells this step fills in or changes. They keep the new value on later steps. To reveal working, start a cell as "" and set it here.')
|
|
1658
|
+
}).strict();
|
|
1659
|
+
var TableSpec = z11.object({
|
|
1660
|
+
title: z11.string().trim().min(1).max(120),
|
|
1661
|
+
columns: z11.array(Header).min(1).max(MAX_COLUMNS).describe("Column headers, one per data column. Don't include a header for rowHeaders."),
|
|
1662
|
+
rows: z11.array(z11.array(CellValue).min(1).max(MAX_COLUMNS)).min(1).max(MAX_ROWS).describe('Data rows, each with exactly one cell per column. A boolean shows as T or F; "" is a blank cell.'),
|
|
1663
|
+
rowHeaders: z11.array(Header).max(MAX_ROWS).optional().describe("Optional label for each row, e.g. a relation matrix's elements. Exactly one per row."),
|
|
1664
|
+
steps: z11.array(TableStep).min(1).max(MAX_STEPS4).optional().describe("Omit for a static table. With steps, the learner steps through them.")
|
|
1665
|
+
}).strict().superRefine((spec, ctx) => {
|
|
1666
|
+
const rowCount = spec.rows.length;
|
|
1667
|
+
const columnCount = spec.columns.length;
|
|
1668
|
+
spec.rows.forEach((row, i) => {
|
|
1669
|
+
if (row.length !== columnCount) {
|
|
1670
|
+
ctx.addIssue({ code: "custom", path: ["rows", i], message: `row has ${row.length} cells but there are ${columnCount} columns` });
|
|
1671
|
+
}
|
|
1672
|
+
});
|
|
1673
|
+
if (spec.rowHeaders && spec.rowHeaders.length !== rowCount) {
|
|
1674
|
+
ctx.addIssue({ code: "custom", path: ["rowHeaders"], message: `${spec.rowHeaders.length} row headers for ${rowCount} rows` });
|
|
1675
|
+
}
|
|
1676
|
+
const checkRow = (row, path) => {
|
|
1677
|
+
if (row >= rowCount) ctx.addIssue({ code: "custom", path, message: `row ${row} is outside the table (${rowCount} rows)` });
|
|
1678
|
+
};
|
|
1679
|
+
const checkColumn = (column, path) => {
|
|
1680
|
+
if (column >= columnCount) ctx.addIssue({ code: "custom", path, message: `column ${column} is outside the table (${columnCount} columns)` });
|
|
1681
|
+
};
|
|
1682
|
+
spec.steps?.forEach((step, i) => {
|
|
1683
|
+
step.highlight?.forEach((h, j) => {
|
|
1684
|
+
const path = ["steps", i, "highlight", j];
|
|
1685
|
+
if (h.row === void 0 && h.column === void 0) ctx.addIssue({ code: "custom", path, message: "a highlight needs a row, a column or both" });
|
|
1686
|
+
if (h.row !== void 0) checkRow(h.row, [...path, "row"]);
|
|
1687
|
+
if (h.column !== void 0) checkColumn(h.column, [...path, "column"]);
|
|
1688
|
+
});
|
|
1689
|
+
step.cells?.forEach((c, j) => {
|
|
1690
|
+
checkRow(c.row, ["steps", i, "cells", j, "row"]);
|
|
1691
|
+
checkColumn(c.column, ["steps", i, "cells", j, "column"]);
|
|
1692
|
+
});
|
|
1693
|
+
});
|
|
1694
|
+
});
|
|
1695
|
+
|
|
1696
|
+
// ../protocol/src/worked-steps.ts
|
|
1697
|
+
import { z as z12 } from "zod";
|
|
1698
|
+
var MAX_STEPS5 = 50;
|
|
1699
|
+
var WorkedStep = z12.object({
|
|
1700
|
+
label: z12.string().trim().min(1).max(40).optional().describe('Optional heading for this part of the working, e.g. "Base case", "Inductive step".'),
|
|
1701
|
+
statement: z12.string().trim().min(1).max(1e3).describe("What this step establishes, mostly as a formula in $...$. For large sums and fractions, put \\displaystyle INSIDE the dollars, e.g. $\\displaystyle\\sum_{i=1}^{n} i$; $$ is not available."),
|
|
1702
|
+
justification: z12.string().trim().min(1).max(500).describe('Why it follows, e.g. "by the inductive hypothesis".')
|
|
1703
|
+
}).strict();
|
|
1704
|
+
var WorkedStepsSpec = z12.object({
|
|
1705
|
+
title: z12.string().trim().min(1).max(120),
|
|
1706
|
+
goal: z12.string().trim().min(1).max(500).optional().describe("Optional statement of what is being shown, e.g. the claim to prove."),
|
|
1707
|
+
steps: z12.array(WorkedStep).min(1).max(MAX_STEPS5)
|
|
1708
|
+
}).strict();
|
|
1709
|
+
|
|
1710
|
+
// ../protocol/src/lesson.ts
|
|
1711
|
+
import { z as z13 } from "zod";
|
|
1712
|
+
var LessonSectionKind = z13.enum(["prose", "algorithm_trace", "code_exercise", "code_walkthrough", "composition", "graph", "multiple_choice", "project_milestone", "set_diagram", "table", "worked_steps"]);
|
|
1713
|
+
var MAX_LESSON_SECTIONS = 10;
|
|
1714
|
+
var LessonOutlineFields = z13.object({
|
|
1715
|
+
title: z13.string().trim().min(1).max(120),
|
|
1716
|
+
sections: z13.array(
|
|
1717
|
+
z13.object({
|
|
1718
|
+
title: z13.string().trim().min(1).max(120),
|
|
1719
|
+
kind: LessonSectionKind.describe(
|
|
1720
|
+
"prose = write_lesson_text; multiple_choice = ask_multiple_choice (a check); code_exercise = ask_code_exercise (a JavaScript or Python exercise the learner solves and submits); project_milestone = set_project_milestone (project courses only: the milestone the learner builds in their repository); the others = the matching show_* tool."
|
|
1721
|
+
),
|
|
1722
|
+
purpose: z13.string().trim().min(1).max(300).describe("What this section does for the learner, in one sentence.")
|
|
1723
|
+
}).strict()
|
|
1724
|
+
).min(2).max(MAX_LESSON_SECTIONS)
|
|
1725
|
+
}).strict();
|
|
1726
|
+
var LessonOutlineInput = LessonOutlineFields.extend({
|
|
1727
|
+
sections: LessonOutlineFields.shape.sections.describe(`2-${MAX_LESSON_SECTIONS} sections in reading order. Include at least one multiple_choice check, usually after the idea it checks.`)
|
|
1728
|
+
}).strict().superRefine((outline, ctx) => {
|
|
1729
|
+
if (!outline.sections.some((s) => s.kind === "multiple_choice")) {
|
|
1730
|
+
ctx.addIssue({ code: "custom", path: ["sections"], message: "Include at least one multiple_choice check" });
|
|
1731
|
+
}
|
|
1732
|
+
outline.sections.forEach((s, i) => {
|
|
1733
|
+
if (s.kind === "project_milestone") ctx.addIssue({ code: "custom", path: ["sections", i, "kind"], message: "project_milestone is only for project courses" });
|
|
1734
|
+
});
|
|
1735
|
+
});
|
|
1736
|
+
var ProjectLessonOutlineInput = LessonOutlineFields.extend({
|
|
1737
|
+
sections: LessonOutlineFields.shape.sections.describe(
|
|
1738
|
+
`2-${MAX_LESSON_SECTIONS} sections in reading order: what the milestone needs, then exactly one project_milestone section, last.`
|
|
1739
|
+
)
|
|
1740
|
+
}).strict().superRefine((outline, ctx) => {
|
|
1741
|
+
const milestones = outline.sections.filter((s) => s.kind === "project_milestone").length;
|
|
1742
|
+
if (milestones !== 1 || outline.sections.at(-1)?.kind !== "project_milestone") {
|
|
1743
|
+
ctx.addIssue({ code: "custom", path: ["sections"], message: "Include exactly one project_milestone section, as the last section" });
|
|
1744
|
+
}
|
|
1745
|
+
});
|
|
1746
|
+
var LessonTextInput = z13.object({
|
|
1747
|
+
markdown: z13.string().trim().min(1).max(6e3).describe("The section's prose, as markdown with $...$ and $$...$$ maths. Don't repeat the section title as a heading."),
|
|
1748
|
+
revisits: z13.array(z13.string().min(1)).max(5).optional().describe("sectionIds from <previous_lesson> this section revisits. The page links back to them, so don't write links yourself.")
|
|
1749
|
+
}).strict();
|
|
1750
|
+
var LessonStatus = z13.enum(["generating", "ready", "failed", "finished"]);
|
|
1751
|
+
var LessonOutlineView = z13.object({
|
|
1752
|
+
title: z13.string(),
|
|
1753
|
+
sections: z13.array(z13.object({ title: z13.string(), kind: LessonSectionKind }).strict())
|
|
1754
|
+
}).strict();
|
|
1755
|
+
var LessonView = z13.object({
|
|
1756
|
+
id: z13.string(),
|
|
1757
|
+
courseId: z13.string(),
|
|
1758
|
+
topicId: z13.string(),
|
|
1759
|
+
topicTitle: z13.string(),
|
|
1760
|
+
position: z13.number().int().nonnegative(),
|
|
1761
|
+
status: LessonStatus,
|
|
1762
|
+
version: z13.number().int().positive().nullable(),
|
|
1763
|
+
outline: LessonOutlineView.nullable(),
|
|
1764
|
+
sections: z13.array(
|
|
1765
|
+
z13.discriminatedUnion("kind", [
|
|
1766
|
+
z13.object({
|
|
1767
|
+
id: z13.string(),
|
|
1768
|
+
title: z13.string(),
|
|
1769
|
+
kind: z13.literal("prose"),
|
|
1770
|
+
markdown: z13.string(),
|
|
1771
|
+
/** Earlier sections this one revisits, for links back to exactly what the learner saw. */
|
|
1772
|
+
revisits: z13.array(z13.object({ lessonId: z13.string(), sectionId: z13.string(), title: z13.string(), lessonTitle: z13.string() }).strict())
|
|
1773
|
+
}).strict(),
|
|
1774
|
+
z13.object({ id: z13.string(), title: z13.string(), kind: z13.literal("artifact"), artifact: z13.unknown() }).strict()
|
|
1775
|
+
])
|
|
1776
|
+
),
|
|
1777
|
+
checks: z13.object({ total: z13.number().int().nonnegative(), answered: z13.number().int().nonnegative() }).strict(),
|
|
1778
|
+
/** The course's current syllabus version, so a page can notice a change made while it was open. */
|
|
1779
|
+
syllabusVersion: z13.number().int().positive().nullable(),
|
|
1780
|
+
/** Sections the latest version added or changed, highlighted for the learner, and why. */
|
|
1781
|
+
changedSectionIds: z13.array(z13.string()),
|
|
1782
|
+
changeReason: z13.string().nullable(),
|
|
1783
|
+
/** Whether the learner can finish it now: fully written and every check answered. */
|
|
1784
|
+
canFinish: z13.boolean(),
|
|
1785
|
+
error: z13.string().nullable(),
|
|
1786
|
+
/** A failure the learner fixes elsewhere: "lesson-model" means the lesson model chosen in Settings can't be used. */
|
|
1787
|
+
errorAction: z13.enum(["lesson-model"]).nullable(),
|
|
1788
|
+
createdAt: z13.string().datetime(),
|
|
1789
|
+
finishedAt: z13.string().datetime().nullable()
|
|
1790
|
+
}).strict();
|
|
1791
|
+
var CourseLessonsView = z13.object({
|
|
1792
|
+
topics: z13.array(
|
|
1793
|
+
z13.object({
|
|
1794
|
+
topicId: z13.string(),
|
|
1795
|
+
title: z13.string(),
|
|
1796
|
+
lesson: z13.object({ id: z13.string(), status: LessonStatus }).strict().nullable()
|
|
1797
|
+
}).strict()
|
|
1798
|
+
),
|
|
1799
|
+
/** The lesson to show: the first unfinished one, or the last one once all are finished. */
|
|
1800
|
+
currentLessonId: z13.string().nullable(),
|
|
1801
|
+
/** The next topic without a lesson, if the learner may start it now. */
|
|
1802
|
+
nextTopicId: z13.string().nullable()
|
|
1803
|
+
}).strict();
|
|
1804
|
+
var SectionTitle = z13.string().trim().min(1).max(120);
|
|
1805
|
+
var SectionMarkdown = z13.string().trim().min(1).max(6e3);
|
|
1806
|
+
var Reason = z13.string().trim().min(1).max(300);
|
|
1807
|
+
var ChangeLessonInput = z13.object({
|
|
1808
|
+
reason: Reason.describe('What the learner asked for, in a few words, e.g. "Simpler intro with an example".'),
|
|
1809
|
+
operations: z13.array(
|
|
1810
|
+
z13.discriminatedUnion("op", [
|
|
1811
|
+
z13.object({ op: z13.literal("rewrite"), sectionId: z13.string().min(1), markdown: SectionMarkdown, title: SectionTitle.optional() }).strict().describe("Replace a prose section's text (and optionally its title)."),
|
|
1812
|
+
z13.object({ op: z13.literal("insert"), afterSectionId: z13.string().min(1).nullable(), title: SectionTitle, markdown: SectionMarkdown }).strict().describe("Add a prose section after the given section, or first if null."),
|
|
1813
|
+
z13.object({ op: z13.literal("insert_artifact"), afterSectionId: z13.string().min(1).nullable(), title: SectionTitle, artifactId: z13.string().min(1) }).strict().describe("Add a card you created earlier in this reply (its artifactId) as a section."),
|
|
1814
|
+
z13.object({ op: z13.literal("remove"), sectionId: z13.string().min(1) }).strict(),
|
|
1815
|
+
z13.object({ op: z13.literal("move"), sectionId: z13.string().min(1), afterSectionId: z13.string().min(1).nullable() }).strict()
|
|
1816
|
+
])
|
|
1817
|
+
).min(1).max(10)
|
|
1818
|
+
}).strict();
|
|
1819
|
+
var ChangeSyllabusInput = z13.object({
|
|
1820
|
+
reason: Reason.describe('What the learner asked for, e.g. "Add a topic on vectors before gradients".'),
|
|
1821
|
+
operations: z13.array(
|
|
1822
|
+
z13.discriminatedUnion("op", [
|
|
1823
|
+
z13.object({
|
|
1824
|
+
op: z13.literal("insert"),
|
|
1825
|
+
afterTopicId: z13.string().min(1).nullable().describe("Insert after this topic; null to insert before the first future topic."),
|
|
1826
|
+
title: SectionTitle,
|
|
1827
|
+
summary: z13.string().trim().min(1).max(400),
|
|
1828
|
+
reason: Reason,
|
|
1829
|
+
concepts: z13.array(z13.string().trim().min(1).max(80)).min(1).max(8)
|
|
1830
|
+
}).strict(),
|
|
1831
|
+
z13.object({ op: z13.literal("edit"), topicId: z13.string().min(1), title: SectionTitle.optional(), summary: z13.string().trim().min(1).max(400).optional() }).strict(),
|
|
1832
|
+
z13.object({ op: z13.literal("remove"), topicId: z13.string().min(1) }).strict(),
|
|
1833
|
+
z13.object({ op: z13.literal("move"), topicId: z13.string().min(1), afterTopicId: z13.string().min(1).nullable() }).strict()
|
|
1834
|
+
])
|
|
1835
|
+
).min(1).max(10)
|
|
1836
|
+
}).strict();
|
|
1837
|
+
var AddToLesson = z13.object({
|
|
1838
|
+
messageId: z13.string().min(1).max(128),
|
|
1839
|
+
afterSectionId: z13.string().min(1).max(128).nullable(),
|
|
1840
|
+
title: SectionTitle
|
|
1841
|
+
}).strict();
|
|
1842
|
+
var NewTopic = z13.object({
|
|
1843
|
+
title: SectionTitle,
|
|
1844
|
+
summary: z13.string().trim().min(1).max(400),
|
|
1845
|
+
concepts: z13.array(z13.string().trim().min(1).max(80)).min(1).max(8)
|
|
1846
|
+
}).strict();
|
|
1847
|
+
var AdaptSyllabusInput = z13.object({
|
|
1848
|
+
reason: Reason.describe('Shown to the learner, with the evidence, e.g. "Added a chain rule refresher: you missed 3 of 4 checks on derivatives".'),
|
|
1849
|
+
operation: z13.discriminatedUnion("op", [
|
|
1850
|
+
NewTopic.extend({ op: z13.literal("insert"), afterTopicId: z13.string().min(1).nullable().describe("null = straight after this lesson's topic") }).strict(),
|
|
1851
|
+
z13.object({ op: z13.literal("split"), topicId: z13.string().min(1), into: z13.array(NewTopic).min(2).max(3) }).strict(),
|
|
1852
|
+
z13.object({ op: z13.literal("move"), topicId: z13.string().min(1), afterTopicId: z13.string().min(1).nullable() }).strict()
|
|
1853
|
+
])
|
|
1854
|
+
}).strict();
|
|
1855
|
+
|
|
1856
|
+
// ../protocol/src/memory.ts
|
|
1857
|
+
import { z as z14 } from "zod";
|
|
1858
|
+
var MemoryKind = z14.enum(["goal", "preference", "misconception", "known"]);
|
|
1859
|
+
var RememberKind = z14.enum(["goal", "preference", "misconception"]);
|
|
1860
|
+
var MemoryText = z14.string().trim().min(1).max(300);
|
|
1861
|
+
var RememberInput = z14.object({
|
|
1862
|
+
kind: RememberKind.describe("goal = what they want to learn or do; preference = how they like to learn; misconception = something they believe that is wrong."),
|
|
1863
|
+
text: MemoryText.describe("One short sentence about the learner. Never include the answer to a check they haven't answered."),
|
|
1864
|
+
concept: z14.string().trim().min(1).max(80).optional().describe("Required for a misconception: the concept it is about. Use the exact name from the check or from their record, so it can be linked to their answers."),
|
|
1865
|
+
replaces: z14.string().min(1).optional().describe("The id of a known memory this one corrects or updates.")
|
|
1866
|
+
}).strict().superRefine((input, ctx) => {
|
|
1867
|
+
if (input.kind === "misconception" && !input.concept) {
|
|
1868
|
+
ctx.addIssue({ code: "custom", path: ["concept"], message: "A misconception needs a concept" });
|
|
1869
|
+
}
|
|
1870
|
+
});
|
|
1871
|
+
var MemoryBasis = z14.enum(["wrong_answer", "chat", "import"]);
|
|
1872
|
+
var MemoryView = z14.object({
|
|
1873
|
+
id: z14.string(),
|
|
1874
|
+
kind: MemoryKind,
|
|
1875
|
+
held: z14.boolean(),
|
|
1876
|
+
text: z14.string().nullable(),
|
|
1877
|
+
concept: z14.string().nullable(),
|
|
1878
|
+
basis: MemoryBasis.nullable(),
|
|
1879
|
+
/** For basis `import`, the note it was drawn from. Null otherwise, and while held. */
|
|
1880
|
+
source: z14.object({ noteId: z14.string(), importId: z14.string(), importName: z14.string(), path: z14.string(), title: z14.string() }).strict().nullable(),
|
|
1881
|
+
createdAt: z14.string().datetime(),
|
|
1882
|
+
editedAt: z14.string().datetime().nullable()
|
|
1883
|
+
}).strict();
|
|
1884
|
+
var MemoryEdit = z14.object({ text: MemoryText }).strict();
|
|
1885
|
+
var MemoryBulkDelete = z14.object({ basis: z14.literal("import") }).strict();
|
|
1886
|
+
|
|
1887
|
+
// ../protocol/src/document.ts
|
|
1888
|
+
import { z as z15 } from "zod";
|
|
1889
|
+
var MAX_DOCUMENT_BYTES = 25 * 1024 * 1024;
|
|
1890
|
+
var DocumentView = z15.object({
|
|
1891
|
+
id: z15.string(),
|
|
1892
|
+
sessionId: z15.string(),
|
|
1893
|
+
messageId: z15.string().nullable(),
|
|
1894
|
+
filename: z15.string(),
|
|
1895
|
+
kind: z15.enum(["pdf", "pptx"]),
|
|
1896
|
+
byteSize: z15.number().int(),
|
|
1897
|
+
pageCount: z15.number().int(),
|
|
1898
|
+
pagesWithText: z15.number().int(),
|
|
1899
|
+
status: z15.literal("ready"),
|
|
1900
|
+
createdAt: z15.string().datetime()
|
|
1901
|
+
});
|
|
1902
|
+
|
|
1903
|
+
// ../protocol/src/vault.ts
|
|
1904
|
+
import { z as z17 } from "zod";
|
|
1905
|
+
|
|
1906
|
+
// ../protocol/src/knowledge.ts
|
|
1907
|
+
import { z as z16 } from "zod";
|
|
1908
|
+
var NoteRef = z16.string().regex(/^n\d{1,3}$/);
|
|
1909
|
+
var ConceptName2 = z16.string().trim().min(1).max(80);
|
|
1910
|
+
var MAX_PROPOSED_CONCEPTS = 30;
|
|
1911
|
+
var MAX_PROPOSED_EDGES = 40;
|
|
1912
|
+
var MAX_PROPOSED_MEMORIES = 30;
|
|
1913
|
+
var ConceptEdgeKind = z16.enum(["prerequisite", "related"]);
|
|
1914
|
+
var RecordFromNotesInput = z16.object({
|
|
1915
|
+
concepts: z16.array(
|
|
1916
|
+
z16.object({
|
|
1917
|
+
name: ConceptName2.describe("A name from <existing_concepts> or <vault_tags> when one fits. Otherwise a new name, written as it appears in the notes."),
|
|
1918
|
+
notes: z16.array(NoteRef).min(1).max(20).describe("The refs of the notes that cover it.")
|
|
1919
|
+
}).strict()
|
|
1920
|
+
).max(MAX_PROPOSED_CONCEPTS),
|
|
1921
|
+
edges: z16.array(
|
|
1922
|
+
z16.object({
|
|
1923
|
+
from: ConceptName2,
|
|
1924
|
+
to: ConceptName2,
|
|
1925
|
+
kind: ConceptEdgeKind.describe("prerequisite = from must be understood before to; related = they're closely linked."),
|
|
1926
|
+
note: NoteRef.describe("The ref of the note that shows this link.")
|
|
1927
|
+
}).strict()
|
|
1928
|
+
).max(MAX_PROPOSED_EDGES).describe("Edges between concepts named in this call or in <existing_concepts>."),
|
|
1929
|
+
memories: z16.array(
|
|
1930
|
+
z16.object({
|
|
1931
|
+
kind: z16.enum(["known", "goal", "misconception"]).describe("known = the notes cover this concept; goal = a goal the notes state; misconception = a wrong belief the notes state."),
|
|
1932
|
+
text: MemoryText.describe("One short sentence about the learner."),
|
|
1933
|
+
concept: ConceptName2.optional().describe("Required for known and misconception: a concept named in this call or in <existing_concepts>."),
|
|
1934
|
+
note: NoteRef.describe("The ref of the note it comes from.")
|
|
1935
|
+
}).strict()
|
|
1936
|
+
).max(MAX_PROPOSED_MEMORIES)
|
|
1937
|
+
}).strict();
|
|
1938
|
+
var DistillationStatus = z16.enum(["idle", "queued", "running", "cancelled", "failed"]);
|
|
1939
|
+
var DistillationView = z16.object({
|
|
1940
|
+
status: DistillationStatus,
|
|
1941
|
+
pendingNotes: z16.number().int(),
|
|
1942
|
+
groups: z16.number().int(),
|
|
1943
|
+
groupsDone: z16.number().int(),
|
|
1944
|
+
error: z16.string().nullable(),
|
|
1945
|
+
/** Concepts and memories drawn from this import's notes so far. */
|
|
1946
|
+
concepts: z16.number().int(),
|
|
1947
|
+
memories: z16.number().int()
|
|
1948
|
+
}).strict();
|
|
1949
|
+
var ConceptGraph = z16.object({
|
|
1950
|
+
concepts: z16.array(z16.object({ id: z16.string(), name: z16.string(), notes: z16.array(z16.string()) }).strict()),
|
|
1951
|
+
edges: z16.array(z16.object({ from: z16.string(), to: z16.string(), kind: ConceptEdgeKind, notes: z16.array(z16.string()) }).strict())
|
|
1952
|
+
}).strict();
|
|
1953
|
+
|
|
1954
|
+
// ../protocol/src/vault.ts
|
|
1955
|
+
var MAX_VAULT_FILES = 1e4;
|
|
1956
|
+
var MAX_NOTE_CHARS = 1e6;
|
|
1957
|
+
var MAX_VAULT_BYTES = 64 * 1024 * 1024;
|
|
1958
|
+
var MAX_PATH_CHARS = 512;
|
|
1959
|
+
var VaultFile = z17.object({
|
|
1960
|
+
/** The file's path inside the vault, with `/` between folders, e.g. `Maths/Recursion.md`. */
|
|
1961
|
+
path: z17.string().min(1).max(MAX_PATH_CHARS),
|
|
1962
|
+
text: z17.string().max(MAX_NOTE_CHARS)
|
|
1963
|
+
}).strict();
|
|
1964
|
+
var VaultFiles = z17.array(VaultFile).max(MAX_VAULT_FILES);
|
|
1965
|
+
var VaultName = z17.string().trim().min(1).max(120);
|
|
1966
|
+
var VaultImportInput = z17.object({ name: VaultName, files: VaultFiles }).strict();
|
|
1967
|
+
var VaultSnapshotInput = z17.object({ files: VaultFiles }).strict();
|
|
1968
|
+
var VaultImportView = z17.object({
|
|
1969
|
+
id: z17.string(),
|
|
1970
|
+
name: z17.string(),
|
|
1971
|
+
source: z17.literal("obsidian"),
|
|
1972
|
+
noteCount: z17.number().int(),
|
|
1973
|
+
createdAt: z17.string().datetime(),
|
|
1974
|
+
updatedAt: z17.string().datetime(),
|
|
1975
|
+
/** Distilling its notes into concepts and memories, which starts after every import (ADR-014). */
|
|
1976
|
+
distillation: DistillationView
|
|
1977
|
+
}).strict();
|
|
1978
|
+
var SkipReason = z17.enum(["not_markdown", "hidden", "bad_path", "duplicate", "too_long", "symlink", "generated"]);
|
|
1979
|
+
var VaultImportResult = z17.object({
|
|
1980
|
+
import: VaultImportView,
|
|
1981
|
+
added: z17.number().int(),
|
|
1982
|
+
updated: z17.number().int(),
|
|
1983
|
+
removed: z17.number().int(),
|
|
1984
|
+
unchanged: z17.number().int(),
|
|
1985
|
+
skippedCount: z17.number().int(),
|
|
1986
|
+
skipped: z17.array(z17.object({ path: z17.string(), reason: SkipReason }).strict()),
|
|
1987
|
+
/** Links or tags left out because a note or the vault had more than the limit. */
|
|
1988
|
+
truncated: z17.boolean()
|
|
1989
|
+
}).strict();
|
|
1990
|
+
var NoteView = z17.object({
|
|
1991
|
+
id: z17.string(),
|
|
1992
|
+
importId: z17.string(),
|
|
1993
|
+
path: z17.string(),
|
|
1994
|
+
title: z17.string(),
|
|
1995
|
+
aliases: z17.array(z17.string()),
|
|
1996
|
+
tags: z17.array(z17.string()),
|
|
1997
|
+
body: z17.string(),
|
|
1998
|
+
updatedAt: z17.string().datetime()
|
|
1999
|
+
}).strict();
|
|
2000
|
+
var NoteGraph = z17.object({
|
|
2001
|
+
notes: z17.array(z17.object({ id: z17.string(), path: z17.string(), title: z17.string(), tags: z17.array(z17.string()) }).strict()),
|
|
2002
|
+
links: z17.array(z17.object({ from: z17.string(), to: z17.string().nullable(), target: z17.string(), kind: z17.enum(["link", "embed"]) }).strict())
|
|
2003
|
+
}).strict();
|
|
2004
|
+
var WHOLE_GRAPH_NOTES = 500;
|
|
2005
|
+
var MAX_GRAPH_VIEW_NOTES = 500;
|
|
2006
|
+
var MAX_GRAPH_VIEW_NODES = 1e3;
|
|
2007
|
+
var MAX_GRAPH_VIEW_EDGES = 5e3;
|
|
2008
|
+
var MAX_GRAPH_FACETS = 200;
|
|
2009
|
+
var NoteGraphViewQuery = z17.object({
|
|
2010
|
+
/** `auto` draws the whole graph when at most WHOLE_GRAPH_NOTES notes match, and the local graph otherwise. */
|
|
2011
|
+
mode: z17.enum(["auto", "local"]).default("auto"),
|
|
2012
|
+
/** The note the local graph is drawn around. Defaults to the matching note with the most connections. */
|
|
2013
|
+
focus: z17.string().max(64).optional(),
|
|
2014
|
+
/** How many hops from the focus the local graph reaches. Sharing a tag or concept is one hop, as a link is. */
|
|
2015
|
+
depth: z17.coerce.number().int().min(1).max(3).default(2),
|
|
2016
|
+
/** Only notes carrying this tag, or one nested under it (`maths` matches `maths/algebra`). */
|
|
2017
|
+
tag: z17.string().max(200).optional(),
|
|
2018
|
+
/** Only notes in this folder or below it, without a trailing `/`. */
|
|
2019
|
+
folder: z17.string().max(512).optional()
|
|
2020
|
+
}).strict();
|
|
2021
|
+
var NoteGraphNodeKind = z17.enum(["note", "ghost", "tag", "concept"]);
|
|
2022
|
+
var NoteGraphEdgeKind = z17.enum(["link", "tag", "concept", "prerequisite", "related"]);
|
|
2023
|
+
var NoteGraphView = z17.object({
|
|
2024
|
+
mode: z17.enum(["whole", "local"]),
|
|
2025
|
+
focus: z17.string().nullable(),
|
|
2026
|
+
depth: z17.number().int(),
|
|
2027
|
+
totalNotes: z17.number().int(),
|
|
2028
|
+
/** Notes matching the filters, drawn or not. */
|
|
2029
|
+
matchingNotes: z17.number().int(),
|
|
2030
|
+
/** Whether the limits left matching nodes or edges out of the drawing. */
|
|
2031
|
+
truncated: z17.boolean(),
|
|
2032
|
+
nodes: z17.array(
|
|
2033
|
+
z17.object({
|
|
2034
|
+
id: z17.string(),
|
|
2035
|
+
kind: NoteGraphNodeKind,
|
|
2036
|
+
label: z17.string(),
|
|
2037
|
+
path: z17.string().optional(),
|
|
2038
|
+
notes: z17.number().int().optional(),
|
|
2039
|
+
hops: z17.number().int().optional()
|
|
2040
|
+
}).strict()
|
|
2041
|
+
),
|
|
2042
|
+
edges: z17.array(z17.object({ from: z17.string(), to: z17.string(), kind: NoteGraphEdgeKind }).strict()),
|
|
2043
|
+
tags: z17.array(z17.object({ name: z17.string(), notes: z17.number().int() }).strict()),
|
|
2044
|
+
folders: z17.array(z17.object({ path: z17.string(), notes: z17.number().int() }).strict())
|
|
2045
|
+
}).strict();
|
|
2046
|
+
var NoteSummary = z17.object({ id: z17.string(), title: z17.string(), path: z17.string() }).strict();
|
|
2047
|
+
|
|
2048
|
+
// ../protocol/src/index.ts
|
|
2049
|
+
var artifactKinds = {
|
|
2050
|
+
algorithm_trace: {
|
|
2051
|
+
version: 1,
|
|
2052
|
+
toolName: "show_algorithm_trace",
|
|
2053
|
+
description: "Show the learner an interactive step-by-step trace of an algorithm running over a sequence (e.g. sliding window, two pointers, binary search, a simple sort). The learner steps through it with play/pause/step controls. Use it when watching state change step by step will make the idea click. Keep traces short (roughly 5-20 steps) and make each step's explanation say what changed and why. A code pane is optional: add `code` and each step's `lines` only when the code itself is the point, such as how an implementation's lines move the state, and leave it out when the idea matters more than any code. Write that code in the programming language the learner has shown proficiency in according to <learner_memories>; if they show none, use Python or pseudocode. Keep the code short, and highlight the lines each step is running. For code that doesn't move over a sequence, such as a plain function or a React render, use show_code_walkthrough instead of inventing an array.",
|
|
2054
|
+
spec: AlgorithmTraceSpec,
|
|
2055
|
+
input: artifactMathInput(AlgorithmTraceSpec, ["title", "steps.*.explanation"])
|
|
2056
|
+
},
|
|
2057
|
+
code_exercise: {
|
|
2058
|
+
version: 1,
|
|
2059
|
+
toolName: "ask_code_exercise",
|
|
2060
|
+
description: "Give the learner a short JavaScript or Python coding exercise to solve in an editor in the UI, after teaching an idea they can now practise by writing code. Use the language they are learning. They run the visible cases as often as they like, then submit once; their result is reported back to you on the next turn, so don't reveal or hint at a solution in your reply. Keep it to one small function or program (a few to about 30 lines), with 3-8 fast cases. Two kinds of case: a call case calls `functionName` (defined at the top level) with JSON arguments and compares its return value as JSON (key order ignored; in Python, None is null and tuples are lists), and a stdio case runs the whole program with the case's stdin and compares what it prints (trailing whitespace and trailing blank lines ignored). Prefer call cases; use stdio for programs that read input and print. JavaScript runs as plain JavaScript with no DOM, network, modules, timers or Node APIs: only console, the global `stdin` string and `readLine()` (the next input line, or null). Python runs in Pyodide with the standard library only: no network, files, threads, subprocesses or packages to install; read input with input() or sys.stdin and print with print(). Write a correct, deterministic referenceSolution in the same language: Mivra runs it on every case to get the expected results, rejecting the exercise if it fails, and never shows it. Hide a case or two that check edge cases. The starter code should give the function's signature (or the program's outline) and no solution.",
|
|
2061
|
+
spec: CodeExerciseSpec,
|
|
2062
|
+
input: artifactMathInput(CodeExerciseInput, ["title"])
|
|
2063
|
+
},
|
|
2064
|
+
code_walkthrough: {
|
|
2065
|
+
version: 1,
|
|
2066
|
+
toolName: "show_code_walkthrough",
|
|
2067
|
+
description: 'Show the learner a step-by-step walkthrough of a short piece of code that isn\'t about a sequence: a plain function\'s parameters, locals and return value, or a React component\'s renders, handlers and state updates. Each step highlights the source lines it is at and gives a complete snapshot of the visible state (`variables`) and the visible output (`output`, plain text such as printed lines or what the page shows, e.g. "Count: 0"); nothing carries over between steps, so repeat whatever still applies and use [] or "" for none. The source stays the same on every step. Use show_algorithm_trace instead for an algorithm moving over an array or other sequence, and show_graph for a component hierarchy. Keep the code short (a few to about 20 lines) and the walkthrough short (roughly 3-12 steps). Write the code in the language the concept belongs to (JSX for React); for a language-neutral idea, use the language the learner knows from <learner_memories>, else Python or pseudocode. The snapshots are your illustration, not a real run, so get them right. For React, keep the state a render or handler sees apart from updates it queues: inside a handler, state still has the value from the render it belongs to (name it, e.g. "handler.count" = 0, with "queued update" = "count + 1"), and the new value and its output appear only at the next render\'s step.',
|
|
2068
|
+
spec: CodeWalkthroughSpec,
|
|
2069
|
+
input: artifactMathInput(CodeWalkthroughSpec, ["title", "steps.*.explanation"])
|
|
2070
|
+
},
|
|
2071
|
+
composition: compositionArtifactKind,
|
|
2072
|
+
graph: {
|
|
2073
|
+
version: 1,
|
|
2074
|
+
toolName: "show_graph",
|
|
2075
|
+
description: `Show the learner a graph or tree, drawn for you, optionally with steps they can walk through. Use it for graphs, trees, BFS, DFS, shortest paths, spanning trees and tree traversals, whenever seeing the structure or watching an algorithm move over it will help. Never give coordinates: the layout is automatic. For a binary search tree or binary tree traversal, set kind to tree and give every edge a side, so a lone left child and a lone right child are drawn differently. The automatic layout may draw crossing edges that mean nothing, even when the graph is planar, so don't use this to show whether a graph is planar. Keep it small enough to read (roughly 4-15 nodes, 5-20 steps) and make each step's explanation say what changed and why. For a component hierarchy (such as React components), set kind to tree and directed to true, with one node per component instance (distinct ids for two instances of the same component, labelled with the short component name) and one edge from each parent to each child it renders, labelled with the props it passes (e.g. "count" or "onClick"). Use steps to highlight where state is owned and the nodes and edges its value flows through, with variables for simple state such as count = 1. The nodes and edges stay the same on every step: don't add callback edges back up the tree, and don't suggest that a component's output changes just because it re-renders. To show where things are and how they move between containers, such as names sharing one object, values passing through pipeline stages or tasks moving between a queue and a stack, use show_composition instead.`,
|
|
2076
|
+
spec: GraphSpec,
|
|
2077
|
+
input: artifactMathInput(GraphSpec, ["title", "nodes.*.label", "edges.*.label", "steps.*.explanation"], (spec, ctx) => {
|
|
2078
|
+
spec.nodes.forEach((node, i) => {
|
|
2079
|
+
if (node.label === void 0) checkMathText(node.id, ["nodes", i, "id"], ctx);
|
|
2080
|
+
});
|
|
2081
|
+
})
|
|
2082
|
+
},
|
|
2083
|
+
interview_context: {
|
|
2084
|
+
version: 1,
|
|
2085
|
+
toolName: "ask_interview_context",
|
|
2086
|
+
description: "Course placement interview only: ask the learner once, as the last question of the interview and in the same reply as the placement questions, whether there is anything else they want you to know about what they already understand or want to explore. They answer in their own words in the UI, or leave it blank; the answer is reported back to you with the placement results. Not graded.",
|
|
2087
|
+
spec: InterviewContextSpec,
|
|
2088
|
+
input: artifactMathInput(InterviewContextSpec, ["question"])
|
|
2089
|
+
},
|
|
2090
|
+
multiple_choice: {
|
|
2091
|
+
version: 1,
|
|
2092
|
+
toolName: "ask_multiple_choice",
|
|
2093
|
+
description: "Ask the learner one multiple-choice question to check understanding of a concept you just taught. Exactly one option is correct. Write plausible wrong options that reflect real misconceptions, and give per-option feedback where useful. The learner answers in the UI; the result is reported back to you on the next turn, so do not reveal the answer in your reply. For a code prediction, put the short snippet in a fenced code block in your reply text before this call and ask what it returns, prints or displays; the question and options render maths and plain text only, so never put code fences in them.",
|
|
2094
|
+
spec: MultipleChoiceSpec,
|
|
2095
|
+
input: artifactMathInput(MultipleChoiceSpec, ["question", "options.*.text", "options.*.feedback", "explanation"])
|
|
2096
|
+
},
|
|
2097
|
+
placement_question: {
|
|
2098
|
+
version: 1,
|
|
2099
|
+
toolName: "ask_placement_question",
|
|
2100
|
+
description: `Course placement interview only: ask the learner one quick question to find out what they already know about one concept, before the syllabus is written. Use multiple choice, true/false or yes/no. The UI always adds "Not sure" and "Skip", so never include those as options. The learner answers in the UI and the result is reported back to you, so don't reveal the answer.`,
|
|
2101
|
+
spec: PlacementQuestionSpec,
|
|
2102
|
+
input: artifactMathInput(PlacementQuestionSpec, ["question", "options.*.text", "explanation"])
|
|
2103
|
+
},
|
|
2104
|
+
project_milestone: {
|
|
2105
|
+
version: 1,
|
|
2106
|
+
toolName: "set_project_milestone",
|
|
2107
|
+
description: "Project course lessons only: set this lesson's milestone, the step of the project the learner builds next in their own repository, in whatever language they chose. They check it with `mivra check`, which runs their program on each case's input (on stdin, and as a file whose path replaces {input} in their command) and compares what it prints with what your Python referenceSolution prints for that input. Say exactly what to build in spec and exactly what to print in outputFormat, so a program in any language can match it; trailing spaces and trailing blank lines are ignored, everything else counts, and the program must exit with code 0. Write 3-12 small, fast cases, simplest first, that cover the milestone's edge cases. Mivra runs the reference on every case when you call this; if it fails or times out, nothing is saved and you get the reason, so fix it and call again. Use compare run_output only when the program's output is itself a program, such as generated assembly; the reference then prints what running that output should print. Every check also sends the learner's changed files to a code review, which must approve too: it fails hard-coded outputs, code that doesn't use the milestone's concept (say what it must show in reviewFocus) and seriously poor code. Use checkType review, with no cases or reference, for what output can't show (structure, a language feature, concurrency, performance); reviewFocus then says exactly what the code must show. Never show the reference or write the learner's solution.",
|
|
2108
|
+
spec: ProjectMilestoneSpec,
|
|
2109
|
+
input: artifactMathInput(ProjectMilestoneInput, ["title"])
|
|
2110
|
+
},
|
|
2111
|
+
set_diagram: {
|
|
2112
|
+
version: 1,
|
|
2113
|
+
toolName: "show_set_diagram",
|
|
2114
|
+
description: "Show the learner a Venn diagram of 1 to 3 sets, with what each region contains. Use it for set operations (union, intersection, complement, difference) and inclusion-exclusion, not for more than 3 sets. Keep elements short, because they are drawn in their region. Add steps to walk through it: each step highlights exact regions (any of them, including outside every set, which needs `universe`) and says what changed and why.",
|
|
2115
|
+
spec: SetDiagramSpec,
|
|
2116
|
+
input: artifactMathInput(SetDiagramSpec, ["title", "universe", "sets.*.label", "regions.*.elements.*", "steps.*.explanation", "steps.*.variables.*.name", "steps.*.variables.*.value"])
|
|
2117
|
+
},
|
|
2118
|
+
table: {
|
|
2119
|
+
version: 1,
|
|
2120
|
+
toolName: "show_table",
|
|
2121
|
+
description: "Show the learner a table: a truth table, a relation matrix or other tabular working. Use it whenever the content is really rows and columns. Add steps when filling it in or highlighting it one part at a time will help, such as working out a truth table column by column; leave them out for a table to read at a glance. Keep steps short and make each explanation say what changed and why.",
|
|
2122
|
+
spec: TableSpec,
|
|
2123
|
+
input: artifactMathInput(TableSpec, ["title", "columns.*", "rowHeaders.*", "rows.*.*", "steps.*.explanation", "steps.*.cells.*.value"])
|
|
2124
|
+
},
|
|
2125
|
+
worked_steps: {
|
|
2126
|
+
version: 1,
|
|
2127
|
+
toolName: "show_worked_steps",
|
|
2128
|
+
description: "Show the learner a proof, an induction or combinatorics working as a sequence of steps they reveal one at a time, each a statement with its justification. Use it when the reasoning is the point and each line follows from the ones before. Use show_algorithm_trace instead for an algorithm's state changing over a sequence.",
|
|
2129
|
+
spec: WorkedStepsSpec,
|
|
2130
|
+
input: artifactMathInput(WorkedStepsSpec, ["title", "goal", "steps.*.label", "steps.*.statement", "steps.*.justification"])
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
var ArtifactKind = z18.enum(Object.keys(artifactKinds));
|
|
2134
|
+
var ArtifactBase = { id: z18.string(), createdAt: z18.string().datetime() };
|
|
2135
|
+
var MultipleChoiceAttempt = z18.object({ answer: MultipleChoiceAnswer, grade: MultipleChoiceGrade, createdAt: z18.string().datetime() }).strict();
|
|
2136
|
+
var CodeExerciseAttempt = z18.object({ answer: CodeExerciseAnswer, grade: CodeExerciseGrade, createdAt: z18.string().datetime() }).strict();
|
|
2137
|
+
var InterviewContextAttempt = z18.object({ answer: InterviewContextAnswer, grade: InterviewContextGrade, createdAt: z18.string().datetime() }).strict();
|
|
2138
|
+
var MilestoneAttempt = z18.object({ answer: MilestoneCheckView, grade: MilestoneGrade, createdAt: z18.string().datetime() }).strict();
|
|
2139
|
+
var MilestoneReviewAttempt = z18.object({ review: MilestoneReview, createdAt: z18.string().datetime() }).strict();
|
|
2140
|
+
var PlacementAttempt = z18.object({ answer: PlacementAnswer, grade: PlacementGrade, createdAt: z18.string().datetime() }).strict();
|
|
2141
|
+
var ArtifactView = z18.discriminatedUnion("kind", [
|
|
2142
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("algorithm_trace"), version: z18.literal(1), spec: AlgorithmTraceSpec }).strict(),
|
|
2143
|
+
z18.object({
|
|
2144
|
+
...ArtifactBase,
|
|
2145
|
+
kind: z18.literal("code_exercise"),
|
|
2146
|
+
version: z18.literal(1),
|
|
2147
|
+
spec: CodeExercisePublic,
|
|
2148
|
+
latestAttempt: CodeExerciseAttempt.optional()
|
|
2149
|
+
}).strict(),
|
|
2150
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("code_walkthrough"), version: z18.literal(1), spec: CodeWalkthroughSpec }).strict(),
|
|
2151
|
+
CompositionArtifactView,
|
|
2152
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("graph"), version: z18.literal(1), spec: GraphSpec }).strict(),
|
|
2153
|
+
z18.object({
|
|
2154
|
+
...ArtifactBase,
|
|
2155
|
+
kind: z18.literal("interview_context"),
|
|
2156
|
+
version: z18.literal(1),
|
|
2157
|
+
spec: InterviewContextSpec,
|
|
2158
|
+
latestAttempt: InterviewContextAttempt.optional()
|
|
2159
|
+
}).strict(),
|
|
2160
|
+
z18.object({
|
|
2161
|
+
...ArtifactBase,
|
|
2162
|
+
kind: z18.literal("multiple_choice"),
|
|
2163
|
+
version: z18.literal(1),
|
|
2164
|
+
spec: MultipleChoicePublic,
|
|
2165
|
+
latestAttempt: MultipleChoiceAttempt.optional()
|
|
2166
|
+
}).strict(),
|
|
2167
|
+
z18.object({
|
|
2168
|
+
...ArtifactBase,
|
|
2169
|
+
kind: z18.literal("placement_question"),
|
|
2170
|
+
version: z18.literal(1),
|
|
2171
|
+
spec: PlacementQuestionPublic,
|
|
2172
|
+
latestAttempt: PlacementAttempt.optional()
|
|
2173
|
+
}).strict(),
|
|
2174
|
+
z18.object({
|
|
2175
|
+
...ArtifactBase,
|
|
2176
|
+
kind: z18.literal("project_milestone"),
|
|
2177
|
+
version: z18.literal(1),
|
|
2178
|
+
spec: ProjectMilestonePublic,
|
|
2179
|
+
/** The latest `mivra check`: a milestone is checked as often as the learner likes, and each check replaces the last. */
|
|
2180
|
+
latestAttempt: MilestoneAttempt.optional(),
|
|
2181
|
+
/** The latest check's review, if it ran and finished. */
|
|
2182
|
+
latestReview: MilestoneReviewAttempt.optional(),
|
|
2183
|
+
/** Whether the latest check passed the milestone: every case, and the review's approval. */
|
|
2184
|
+
passed: z18.boolean().optional()
|
|
2185
|
+
}).strict(),
|
|
2186
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("set_diagram"), version: z18.literal(1), spec: SetDiagramSpec }).strict(),
|
|
2187
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("table"), version: z18.literal(1), spec: TableSpec }).strict(),
|
|
2188
|
+
z18.object({ ...ArtifactBase, kind: z18.literal("worked_steps"), version: z18.literal(1), spec: WorkedStepsSpec }).strict()
|
|
2189
|
+
]);
|
|
2190
|
+
var CHATGPT_USAGE_LIMIT_ERROR = "ChatGPT usage limit reached. Review your plan or this app's limit in ChatGPT settings.";
|
|
2191
|
+
|
|
2192
|
+
export {
|
|
2193
|
+
AlgorithmTraceSpec,
|
|
2194
|
+
MAX_CASE_OUTPUT_CHARS,
|
|
2195
|
+
EXERCISE_LIMITS,
|
|
2196
|
+
ExerciseCaseInput,
|
|
2197
|
+
CodeExerciseInput,
|
|
2198
|
+
CodeExerciseSpec,
|
|
2199
|
+
toCodeExercisePublic,
|
|
2200
|
+
ExerciseCaseRun,
|
|
2201
|
+
CodeExerciseAnswer,
|
|
2202
|
+
normaliseOutput,
|
|
2203
|
+
expectedFrom,
|
|
2204
|
+
gradeCodeExercise,
|
|
2205
|
+
CodeWalkthroughSpec,
|
|
2206
|
+
CompositionSpec,
|
|
2207
|
+
compositionArtifactKind,
|
|
2208
|
+
StartCourse,
|
|
2209
|
+
PlacementQuestionSpec,
|
|
2210
|
+
toPlacementQuestionPublic,
|
|
2211
|
+
PlacementAnswer,
|
|
2212
|
+
gradePlacementQuestion,
|
|
2213
|
+
InterviewContextSpec,
|
|
2214
|
+
InterviewContextAnswer,
|
|
2215
|
+
gradeInterviewContext,
|
|
2216
|
+
CourseIcon,
|
|
2217
|
+
SyllabusInput,
|
|
2218
|
+
CourseView,
|
|
2219
|
+
GraphSpec,
|
|
2220
|
+
MultipleChoiceSpec,
|
|
2221
|
+
toMultipleChoicePublic,
|
|
2222
|
+
MultipleChoiceAnswer,
|
|
2223
|
+
gradeMultipleChoice,
|
|
2224
|
+
MAX_MILESTONE_STDERR_CHARS,
|
|
2225
|
+
MAX_REVIEW_FILES,
|
|
2226
|
+
MAX_REVIEW_FILE_CHARS,
|
|
2227
|
+
MAX_REVIEW_TOTAL_CHARS,
|
|
2228
|
+
MAX_REVIEW_PATH_CHARS,
|
|
2229
|
+
CommitId,
|
|
2230
|
+
ProjectMilestoneInput,
|
|
2231
|
+
MAX_MILESTONE_DISPUTES,
|
|
2232
|
+
MilestoneDispute,
|
|
2233
|
+
ProjectMilestoneSpec,
|
|
2234
|
+
activeMilestoneCases,
|
|
2235
|
+
toProjectMilestonePublic,
|
|
2236
|
+
MilestoneCases,
|
|
2237
|
+
MilestoneCheckAnswer,
|
|
2238
|
+
gradeMilestone,
|
|
2239
|
+
MilestoneReviewInput,
|
|
2240
|
+
MilestoneReview,
|
|
2241
|
+
reviewVerdict,
|
|
2242
|
+
milestonePassed,
|
|
2243
|
+
MilestoneCheckResult,
|
|
2244
|
+
MilestoneDisputeRequest,
|
|
2245
|
+
CaseDisputeDecision,
|
|
2246
|
+
toMilestoneCheckView,
|
|
2247
|
+
SetDiagramSpec,
|
|
2248
|
+
TableSpec,
|
|
2249
|
+
WorkedStepsSpec,
|
|
2250
|
+
runExerciseCaseIsolated,
|
|
2251
|
+
createPythonCaseRunner,
|
|
2252
|
+
LessonSectionKind,
|
|
2253
|
+
MAX_LESSON_SECTIONS,
|
|
2254
|
+
LessonOutlineInput,
|
|
2255
|
+
ProjectLessonOutlineInput,
|
|
2256
|
+
LessonTextInput,
|
|
2257
|
+
LessonView,
|
|
2258
|
+
CourseLessonsView,
|
|
2259
|
+
ChangeLessonInput,
|
|
2260
|
+
ChangeSyllabusInput,
|
|
2261
|
+
AddToLesson,
|
|
2262
|
+
AdaptSyllabusInput,
|
|
2263
|
+
RememberInput,
|
|
2264
|
+
MemoryView,
|
|
2265
|
+
MemoryEdit,
|
|
2266
|
+
MemoryBulkDelete,
|
|
2267
|
+
MAX_DOCUMENT_BYTES,
|
|
2268
|
+
DocumentView,
|
|
2269
|
+
RecordFromNotesInput,
|
|
2270
|
+
DistillationView,
|
|
2271
|
+
ConceptGraph,
|
|
2272
|
+
MAX_VAULT_FILES,
|
|
2273
|
+
MAX_NOTE_CHARS,
|
|
2274
|
+
MAX_VAULT_BYTES,
|
|
2275
|
+
VaultImportInput,
|
|
2276
|
+
VaultSnapshotInput,
|
|
2277
|
+
VaultImportView,
|
|
2278
|
+
SkipReason,
|
|
2279
|
+
VaultImportResult,
|
|
2280
|
+
NoteView,
|
|
2281
|
+
NoteGraph,
|
|
2282
|
+
WHOLE_GRAPH_NOTES,
|
|
2283
|
+
MAX_GRAPH_VIEW_NOTES,
|
|
2284
|
+
MAX_GRAPH_VIEW_NODES,
|
|
2285
|
+
MAX_GRAPH_VIEW_EDGES,
|
|
2286
|
+
MAX_GRAPH_FACETS,
|
|
2287
|
+
NoteGraphViewQuery,
|
|
2288
|
+
NoteGraphView,
|
|
2289
|
+
NoteSummary,
|
|
2290
|
+
artifactKinds,
|
|
2291
|
+
ArtifactView,
|
|
2292
|
+
CHATGPT_USAGE_LIMIT_ERROR
|
|
2293
|
+
};
|
|
2294
|
+
//# sourceMappingURL=chunk-B47HA6IQ.js.map
|