@okhay-p/mivra 0.1.2 → 0.1.3
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 +1 -0
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/dist/chunk-3RMHLZ2Z.js +736 -0
- package/dist/chunk-3RMHLZ2Z.js.map +7 -0
- package/dist/chunk-EICBRY5M.js +381 -0
- package/dist/chunk-EICBRY5M.js.map +7 -0
- package/dist/chunk-FBDML53R.js +933 -0
- package/dist/chunk-FBDML53R.js.map +7 -0
- package/dist/chunk-KE5ZEREE.js +212 -0
- package/dist/chunk-KE5ZEREE.js.map +7 -0
- package/dist/chunk-PZ5AY32C.js +10 -0
- package/dist/chunk-PZ5AY32C.js.map +7 -0
- package/dist/chunk-TBAR47I6.js +32 -0
- package/dist/chunk-TBAR47I6.js.map +7 -0
- package/dist/cli.js +256 -11188
- package/dist/cli.js.map +4 -4
- package/dist/client-VU3KWV3U.js +12 -0
- package/dist/client-VU3KWV3U.js.map +7 -0
- package/dist/extract-child.js +107 -173
- package/dist/extract-child.js.map +3 -3
- package/dist/key-check-WJ4CVZV5.js +8 -0
- package/dist/key-check-WJ4CVZV5.js.map +7 -0
- package/dist/start-3J3JSJEX.js +10899 -0
- package/dist/start-3J3JSJEX.js.map +7 -0
- package/drizzle/0012_overconfident_the_santerians.sql +66 -0
- package/drizzle/meta/0012_snapshot.json +1741 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +1 -1
- package/web/assets/index-BUYWW1Mc.js +406 -0
- package/web/assets/index-Cmq-m9fI.css +1 -0
- package/web/assets/{render.worker-Bw6rO7Qu.js → render.worker-BEpv9w1x.js} +1 -1
- package/web/index.html +2 -2
- package/web/assets/index-BfT-sp3_.js +0 -406
- package/web/assets/index-FIC4B_yh.css +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../protocol/src/course.ts", "../../protocol/src/lesson.ts", "../../protocol/src/memory.ts", "../../protocol/src/document.ts", "../../protocol/src/vault.ts", "../../protocol/src/index.ts", "../../protocol/src/artifact-math-input.ts", "../../protocol/src/math-text.ts", "../../protocol/src/algorithm-trace.ts", "../../protocol/src/graph.ts", "../../protocol/src/multiple-choice.ts", "../../protocol/src/set-diagram.ts", "../../protocol/src/table.ts", "../../protocol/src/worked-steps.ts"],
|
|
4
|
+
"sourcesContent": ["import { z } from \"zod\";\n\n/**\n * Courses (ADR-011): one learning goal, a placement interview, then a syllabus of ordered topics\n * written by the AI. The learner never approves the syllabus; they change it later through the tutor.\n */\n\nexport const MAX_GOAL_CHARS = 300;\nexport const CourseGoal = z.string().trim().min(1).max(MAX_GOAL_CHARS);\n\n/** Body of POST /courses. */\nexport const StartCourse = z.object({ goal: CourseGoal }).strict();\nexport type StartCourse = z.infer<typeof StartCourse>;\n\nconst ConceptName = z.string().trim().min(1).max(80);\n\n// ---------------------------------------------------------------------------------------------\n// placement_question v1: one interview question. Multiple choice, true/false or yes/no, and the\n// learner can always answer \"Not sure\" or skip it. No confidence rating (owner decision on #1).\n// ---------------------------------------------------------------------------------------------\n\nexport const PlacementQuestionSpec = z\n .object({\n 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.'),\n question: z.string().trim().min(1).max(1000),\n options: z\n .array(z.object({ text: z.string().trim().min(1).max(300) }).strict())\n .min(2)\n .max(5)\n .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.'),\n correctOptionIndex: z.number().int().nonnegative().describe(\"0-based index of the single correct option.\"),\n explanation: z.string().trim().min(1).max(600).describe(\"One or two sentences shown after answering: why the correct option is correct.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n if (spec.correctOptionIndex >= spec.options.length) {\n ctx.addIssue({ code: \"custom\", path: [\"correctOptionIndex\"], message: \"correctOptionIndex must point at one of the options\" });\n }\n const seen = new Map<string, number>();\n spec.options.forEach((option, i) => {\n const key = option.text.normalize(\"NFC\");\n const first = seen.get(key);\n if (first !== undefined) ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: `duplicates option ${first}` });\n else seen.set(key, i);\n if (/^\\s*(not sure|i don'?t know|unsure|skip)\\W*$/i.test(option.text)) {\n ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: \"Leave out Not sure / Skip: the UI always offers them\" });\n }\n });\n });\nexport type PlacementQuestionSpec = z.infer<typeof PlacementQuestionSpec>;\n\n/** What the client sees before answering. */\nexport const PlacementQuestionPublic = z\n .object({ concept: z.string(), question: z.string(), options: z.array(z.object({ text: z.string() }).strict()) })\n .strict();\nexport type PlacementQuestionPublic = z.infer<typeof PlacementQuestionPublic>;\n\nexport const toPlacementQuestionPublic = (spec: PlacementQuestionSpec): PlacementQuestionPublic => ({\n concept: spec.concept,\n question: spec.question,\n options: spec.options.map((o) => ({ text: o.text })),\n});\n\nexport const PlacementAnswer = z.union([\n z.object({ optionIndex: z.number().int().nonnegative() }).strict(),\n z.object({ unsure: z.literal(true) }).strict(),\n z.object({ skipped: z.literal(true) }).strict(),\n]);\nexport type PlacementAnswer = z.infer<typeof PlacementAnswer>;\n\nexport const PlacementResult = z.enum([\"correct\", \"incorrect\", \"unsure\", \"skipped\"]);\nexport type PlacementResult = z.infer<typeof PlacementResult>;\n\nexport const PlacementGrade = z\n .object({ result: PlacementResult, correctOptionIndex: z.number().int().nonnegative(), explanation: z.string() })\n .strict();\nexport type PlacementGrade = z.infer<typeof PlacementGrade>;\n\n/** Deterministic grader. \"Not sure\" counts as not knowing it; a skip is no evidence either way. */\nexport function gradePlacementQuestion(spec: PlacementQuestionSpec, answer: PlacementAnswer): PlacementGrade {\n let result: PlacementResult;\n if (\"optionIndex\" in answer) {\n if (!spec.options[answer.optionIndex]) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);\n result = answer.optionIndex === spec.correctOptionIndex ? \"correct\" : \"incorrect\";\n } else result = \"unsure\" in answer ? \"unsure\" : \"skipped\";\n return { result, correctOptionIndex: spec.correctOptionIndex, explanation: spec.explanation };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Syllabus\n// ---------------------------------------------------------------------------------------------\n\nexport const KnownSource = z.enum([\"memory\", \"test\", \"guess\"]);\nexport type KnownSource = z.infer<typeof KnownSource>;\n\nexport const SyllabusTopicInput = z\n .object({\n title: z.string().trim().min(1).max(120),\n summary: z.string().trim().min(1).max(400).describe(\"What the lesson on this topic will cover, in one or two sentences.\"),\n reason: z.string().trim().min(1).max(300).describe('Why this topic is here for this learner, e.g. \"You missed the question on local minima\".'),\n requestedByLearner: z.boolean().describe(\"True if the learner explicitly asked for this topic. Such topics are never removed automatically.\"),\n concepts: z.array(ConceptName).min(1).max(8).describe(\"Concept names this topic teaches; reuse names from the learner's record and the placement questions.\"),\n })\n .strict();\n\n/** Input of the write_syllabus tool. The server adds ids, version and timestamps. */\nexport const SyllabusInput = z\n .object({\n topics: z.array(SyllabusTopicInput).min(1).max(20).describe(\"The ordered topics, first to learn first. Each topic gets one lesson.\"),\n known: z\n .array(\n z\n .object({\n concept: ConceptName,\n source: KnownSource.describe(\"memory = from their record or memories; test = from this placement interview; guess = your inference\"),\n note: z.string().trim().min(1).max(200),\n })\n .strict(),\n )\n .max(20)\n .describe(\"What the learner already knows or doesn't, each labelled with where that comes from. Shown to the learner.\"),\n })\n .strict()\n .superRefine((input, ctx) => {\n const seen = new Set<string>();\n input.topics.forEach((topic, i) => {\n const key = topic.title.trim().toLowerCase();\n if (seen.has(key)) ctx.addIssue({ code: \"custom\", path: [\"topics\", i, \"title\"], message: \"Topic titles must be distinct\" });\n seen.add(key);\n });\n });\nexport type SyllabusInput = z.infer<typeof SyllabusInput>;\n\nexport const SyllabusTopic = SyllabusTopicInput.extend({ id: z.string() }).strict();\nexport type SyllabusTopic = z.infer<typeof SyllabusTopic>;\n\nexport const SyllabusView = z\n .object({\n version: z.number().int().positive(),\n source: z.enum([\"interview\", \"tutor\", \"adaptive\", \"undo\"]),\n reason: z.string().nullable(),\n changedTopicIds: z.array(z.string()),\n /** Whether the learner can undo this version: an automatic change none of whose new topics has started. */\n canUndo: z.boolean(),\n topics: z.array(SyllabusTopic),\n known: SyllabusInput.shape.known,\n createdAt: z.string().datetime(),\n })\n .strict();\nexport type SyllabusView = z.infer<typeof SyllabusView>;\n\nexport const CourseStatus = z.enum([\"interviewing\", \"active\", \"complete\"]);\nexport type CourseStatus = z.infer<typeof CourseStatus>;\n\nexport const CourseView = z\n .object({\n id: z.string(),\n sessionId: z.string(),\n goal: z.string(),\n status: CourseStatus,\n syllabus: SyllabusView.nullable(),\n /** The tutor's reply that wrote the first syllabus, which ends the placement interview; null if unknown. */\n interviewMessageId: z.string().nullable(),\n createdAt: z.string().datetime(),\n })\n .strict();\nexport type CourseView = z.infer<typeof CourseView>;\n", "import { z } from \"zod\";\n\n/**\n * Lessons (ADR-011): one per syllabus topic, generated when the learner reaches it. The outline comes\n * first, then one tool call per section, so each section validates on its own and appears as soon as it\n * is written. A finished lesson is frozen.\n */\n\n/** Section kinds the outline can plan: prose, or an existing artifact kind by its tool's purpose. */\nexport const LessonSectionKind = z.enum([\"prose\", \"algorithm_trace\", \"graph\", \"multiple_choice\", \"set_diagram\", \"table\", \"worked_steps\"]);\nexport type LessonSectionKind = z.infer<typeof LessonSectionKind>;\n\nexport const MAX_LESSON_SECTIONS = 10;\n\nexport const LessonOutlineInput = z\n .object({\n title: z.string().trim().min(1).max(120),\n sections: z\n .array(\n z\n .object({\n title: z.string().trim().min(1).max(120),\n kind: LessonSectionKind.describe(\"prose = write_lesson_text; multiple_choice = ask_multiple_choice (a check); the others = the matching show_* tool.\"),\n purpose: z.string().trim().min(1).max(300).describe(\"What this section does for the learner, in one sentence.\"),\n })\n .strict(),\n )\n .min(2)\n .max(MAX_LESSON_SECTIONS)\n .describe(`2-${MAX_LESSON_SECTIONS} sections in reading order. Include at least one multiple_choice check, usually after the idea it checks.`),\n })\n .strict()\n .superRefine((outline, ctx) => {\n if (!outline.sections.some((s) => s.kind === \"multiple_choice\")) {\n ctx.addIssue({ code: \"custom\", path: [\"sections\"], message: \"Include at least one multiple_choice check\" });\n }\n });\nexport type LessonOutlineInput = z.infer<typeof LessonOutlineInput>;\n\nexport const LessonTextInput = z\n .object({\n markdown: z.string().trim().min(1).max(6000).describe(\"The section's prose, as markdown with $...$ and $$...$$ maths. Don't repeat the section title as a heading.\"),\n revisits: z\n .array(z.string().min(1))\n .max(5)\n .optional()\n .describe(\"sectionIds from <previous_lesson> this section revisits. The page links back to them, so don't write links yourself.\"),\n })\n .strict();\nexport type LessonTextInput = z.infer<typeof LessonTextInput>;\n\nexport const LessonStatus = z.enum([\"generating\", \"ready\", \"failed\", \"finished\"]);\nexport type LessonStatus = z.infer<typeof LessonStatus>;\n\nexport const LessonOutlineView = z\n .object({\n title: z.string(),\n sections: z.array(z.object({ title: z.string(), kind: LessonSectionKind }).strict()),\n })\n .strict();\n\n/** A lesson as the client sees it. `artifact` holds an ArtifactView, validated by the client's renderer. */\nexport const LessonView = z\n .object({\n id: z.string(),\n courseId: z.string(),\n topicId: z.string(),\n topicTitle: z.string(),\n position: z.number().int().nonnegative(),\n status: LessonStatus,\n version: z.number().int().positive().nullable(),\n outline: LessonOutlineView.nullable(),\n sections: z.array(\n z.discriminatedUnion(\"kind\", [\n z\n .object({\n id: z.string(),\n title: z.string(),\n kind: z.literal(\"prose\"),\n markdown: z.string(),\n /** Earlier sections this one revisits, for links back to exactly what the learner saw. */\n revisits: z.array(z.object({ lessonId: z.string(), sectionId: z.string(), title: z.string(), lessonTitle: z.string() }).strict()),\n })\n .strict(),\n z.object({ id: z.string(), title: z.string(), kind: z.literal(\"artifact\"), artifact: z.unknown() }).strict(),\n ]),\n ),\n checks: z.object({ total: z.number().int().nonnegative(), answered: z.number().int().nonnegative() }).strict(),\n /** The course's current syllabus version, so a page can notice a change made while it was open. */\n syllabusVersion: z.number().int().positive().nullable(),\n /** Sections the latest version added or changed, highlighted for the learner, and why. */\n changedSectionIds: z.array(z.string()),\n changeReason: z.string().nullable(),\n /** Whether the learner can finish it now: fully written and every check answered. */\n canFinish: z.boolean(),\n error: z.string().nullable(),\n createdAt: z.string().datetime(),\n finishedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type LessonView = z.infer<typeof LessonView>;\n\n/** One row per syllabus topic, in syllabus order, with its lesson if one exists. */\nexport const CourseLessonsView = z\n .object({\n topics: z.array(\n z\n .object({\n topicId: z.string(),\n title: z.string(),\n lesson: z.object({ id: z.string(), status: LessonStatus }).strict().nullable(),\n })\n .strict(),\n ),\n /** The lesson to show: the first unfinished one, or the last one once all are finished. */\n currentLessonId: z.string().nullable(),\n /** The next topic without a lesson, if the learner may start it now. */\n nextTopicId: z.string().nullable(),\n })\n .strict();\nexport type CourseLessonsView = z.infer<typeof CourseLessonsView>;\n\nconst SectionTitle = z.string().trim().min(1).max(120);\nconst SectionMarkdown = z.string().trim().min(1).max(6000);\nconst Reason = z.string().trim().min(1).max(300);\n\n/**\n * Input of change_lesson: the tutor's edit of the current lesson, on the learner's request (ADR-011).\n * One call makes one new version; the sections it adds or rewrites are highlighted.\n */\nexport const ChangeLessonInput = z\n .object({\n reason: Reason.describe('What the learner asked for, in a few words, e.g. \"Simpler intro with an example\".'),\n operations: z\n .array(\n z.discriminatedUnion(\"op\", [\n z.object({ op: z.literal(\"rewrite\"), sectionId: z.string().min(1), markdown: SectionMarkdown, title: SectionTitle.optional() }).strict()\n .describe(\"Replace a prose section's text (and optionally its title).\"),\n z.object({ op: z.literal(\"insert\"), afterSectionId: z.string().min(1).nullable(), title: SectionTitle, markdown: SectionMarkdown }).strict()\n .describe(\"Add a prose section after the given section, or first if null.\"),\n z.object({ op: z.literal(\"insert_artifact\"), afterSectionId: z.string().min(1).nullable(), title: SectionTitle, artifactId: z.string().min(1) }).strict()\n .describe(\"Add a card you created earlier in this reply (its artifactId) as a section.\"),\n z.object({ op: z.literal(\"remove\"), sectionId: z.string().min(1) }).strict(),\n z.object({ op: z.literal(\"move\"), sectionId: z.string().min(1), afterSectionId: z.string().min(1).nullable() }).strict(),\n ]),\n )\n .min(1)\n .max(10),\n })\n .strict();\nexport type ChangeLessonInput = z.infer<typeof ChangeLessonInput>;\n\n/** Input of change_syllabus: the tutor's edit of the course's future topics, on the learner's request. */\nexport const ChangeSyllabusInput = z\n .object({\n reason: Reason.describe('What the learner asked for, e.g. \"Add a topic on vectors before gradients\".'),\n operations: z\n .array(\n z.discriminatedUnion(\"op\", [\n z\n .object({\n op: z.literal(\"insert\"),\n afterTopicId: z.string().min(1).nullable().describe(\"Insert after this topic; null to insert before the first future topic.\"),\n title: SectionTitle,\n summary: z.string().trim().min(1).max(400),\n reason: Reason,\n concepts: z.array(z.string().trim().min(1).max(80)).min(1).max(8),\n })\n .strict(),\n z.object({ op: z.literal(\"edit\"), topicId: z.string().min(1), title: SectionTitle.optional(), summary: z.string().trim().min(1).max(400).optional() }).strict(),\n z.object({ op: z.literal(\"remove\"), topicId: z.string().min(1) }).strict(),\n z.object({ op: z.literal(\"move\"), topicId: z.string().min(1), afterTopicId: z.string().min(1).nullable() }).strict(),\n ]),\n )\n .min(1)\n .max(10),\n })\n .strict();\nexport type ChangeSyllabusInput = z.infer<typeof ChangeSyllabusInput>;\n\n/** Body of POST /lessons/{id}/sections: keep a tutor's Explain answer as a new section. */\nexport const AddToLesson = z\n .object({\n messageId: z.string().min(1).max(128),\n afterSectionId: z.string().min(1).max(128).nullable(),\n title: SectionTitle,\n })\n .strict();\nexport type AddToLesson = z.infer<typeof AddToLesson>;\n\nconst NewTopic = z\n .object({\n title: SectionTitle,\n summary: z.string().trim().min(1).max(400),\n concepts: z.array(z.string().trim().min(1).max(80)).min(1).max(8),\n })\n .strict();\n\n/**\n * Input of adapt_syllabus: lesson generation's own change to future topics when the learner struggled\n * (ADR-011). Insert, split or reorder only; never removes a topic. At most one per finished lesson.\n */\nexport const AdaptSyllabusInput = z\n .object({\n 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\".'),\n operation: z.discriminatedUnion(\"op\", [\n NewTopic.extend({ op: z.literal(\"insert\"), afterTopicId: z.string().min(1).nullable().describe(\"null = straight after this lesson's topic\") }).strict(),\n z.object({ op: z.literal(\"split\"), topicId: z.string().min(1), into: z.array(NewTopic).min(2).max(3) }).strict(),\n z.object({ op: z.literal(\"move\"), topicId: z.string().min(1), afterTopicId: z.string().min(1).nullable() }).strict(),\n ]),\n })\n .strict();\nexport type AdaptSyllabusInput = z.infer<typeof AdaptSyllabusInput>;\n", "import { z } from \"zod\";\n\n/** Memory entries are the model's inferences about the learner, kept apart from graded evidence (ADR-009). */\n\nexport const MemoryKind = z.enum([\"goal\", \"preference\", \"misconception\"]);\nexport type MemoryKind = z.infer<typeof MemoryKind>;\n\nconst MemoryText = z.string().trim().min(1).max(300);\n\n/** The input of the remember tool. Source, timestamps and basis are set by the server, not the model. */\nexport const RememberInput = z\n .object({\n kind: MemoryKind.describe(\"goal = what they want to learn or do; preference = how they like to learn; misconception = something they believe that is wrong.\"),\n text: MemoryText.describe(\"One short sentence about the learner. Never include the answer to a check they haven't answered.\"),\n concept: z.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.\"),\n replaces: z.string().min(1).optional().describe(\"The id of a known memory this one corrects or updates.\"),\n })\n .strict()\n .superRefine((input, ctx) => {\n // Without a concept a misconception can't be linked to a wrong answer (ADR-009).\n if (input.kind === \"misconception\" && !input.concept) {\n ctx.addIssue({ code: \"custom\", path: [\"concept\"], message: \"A misconception needs a concept\" });\n }\n });\nexport type RememberInput = z.infer<typeof RememberInput>;\n\n/** How a memory is supported: a graded wrong answer, or only something said in chat. */\nexport const MemoryBasis = z.enum([\"wrong_answer\", \"chat\"]);\nexport type MemoryBasis = z.infer<typeof MemoryBasis>;\n\n/**\n * A memory as the learner sees it in the memory panel. A memory written while a check was unanswered\n * could give that check's answer away, so until the check is answered it is `held`, without its content.\n */\nexport const MemoryView = z\n .object({\n id: z.string(),\n kind: MemoryKind,\n held: z.boolean(),\n text: z.string().nullable(),\n concept: z.string().nullable(),\n basis: MemoryBasis.nullable(),\n createdAt: z.string().datetime(),\n editedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type MemoryView = z.infer<typeof MemoryView>;\n\nexport const MemoryEdit = z.object({ text: MemoryText }).strict();\n", "import { z } from \"zod\";\n\n/** The largest file the learner can upload (ADR-010). The server enforces it while reading. */\nexport const MAX_DOCUMENT_BYTES = 25 * 1024 * 1024;\n\n/** What a client sees of an uploaded document. Its text stays on the server. */\nexport const DocumentView = z.object({\n id: z.string(),\n sessionId: z.string(),\n messageId: z.string().nullable(),\n filename: z.string(),\n kind: z.enum([\"pdf\", \"pptx\"]),\n byteSize: z.number().int(),\n pageCount: z.number().int(),\n pagesWithText: z.number().int(),\n status: z.literal(\"ready\"),\n createdAt: z.string().datetime(),\n});\nexport type DocumentView = z.infer<typeof DocumentView>;\n", "import { z } from \"zod\";\n\n/**\n * Importing a learner's Obsidian vault (ADR-014). A vault is hostile input (ADR-010), so every size is capped.\n * Clients send only Markdown files; the server checks each path again and skips anything else.\n */\n\n/** Most files one import can send. */\nexport const MAX_VAULT_FILES = 10_000;\n/** Longest note, in characters. */\nexport const MAX_NOTE_CHARS = 1_000_000;\n/** Largest import request body. */\nexport const MAX_VAULT_BYTES = 64 * 1024 * 1024;\nconst MAX_PATH_CHARS = 512;\n\nexport const VaultFile = z\n .object({\n /** The file's path inside the vault, with `/` between folders, e.g. `Maths/Recursion.md`. */\n path: z.string().min(1).max(MAX_PATH_CHARS),\n text: z.string().max(MAX_NOTE_CHARS),\n })\n .strict();\nexport type VaultFile = z.infer<typeof VaultFile>;\n\nconst VaultFiles = z.array(VaultFile).max(MAX_VAULT_FILES);\nconst VaultName = z.string().trim().min(1).max(120);\n\n/** Starts a new import. The name tells imports apart, so it's unique; the CLI defaults it to the vault folder's name. */\nexport const VaultImportInput = z.object({ name: VaultName, files: VaultFiles }).strict();\nexport type VaultImportInput = z.infer<typeof VaultImportInput>;\n\n/** Replaces an import's files with a new snapshot of the vault. */\nexport const VaultSnapshotInput = z.object({ files: VaultFiles }).strict();\nexport type VaultSnapshotInput = z.infer<typeof VaultSnapshotInput>;\n\nexport const VaultImportView = z\n .object({\n id: z.string(),\n name: z.string(),\n source: z.literal(\"obsidian\"),\n noteCount: z.number().int(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n })\n .strict();\nexport type VaultImportView = z.infer<typeof VaultImportView>;\n\n/**\n * Why a file wasn't imported. `too_long` is a note over MAX_NOTE_CHARS and `symlink` a link inside a zipped\n * vault; both are reported by the zip upload and by clients that check sizes before sending.\n */\nexport const SkipReason = z.enum([\"not_markdown\", \"hidden\", \"bad_path\", \"duplicate\", \"too_long\", \"symlink\"]);\nexport type SkipReason = z.infer<typeof SkipReason>;\n\n/** What one import or re-import changed. `skipped` lists at most a few paths; `skippedCount` counts them all. */\nexport const VaultImportResult = z\n .object({\n import: VaultImportView,\n added: z.number().int(),\n updated: z.number().int(),\n removed: z.number().int(),\n unchanged: z.number().int(),\n skippedCount: z.number().int(),\n skipped: z.array(z.object({ path: z.string(), reason: SkipReason }).strict()),\n /** Links or tags left out because a note or the vault had more than the limit. */\n truncated: z.boolean(),\n })\n .strict();\nexport type VaultImportResult = z.infer<typeof VaultImportResult>;\n\nexport const NoteView = z\n .object({\n id: z.string(),\n importId: z.string(),\n path: z.string(),\n title: z.string(),\n aliases: z.array(z.string()),\n tags: z.array(z.string()),\n body: z.string(),\n updatedAt: z.string().datetime(),\n })\n .strict();\nexport type NoteView = z.infer<typeof NoteView>;\n\n/**\n * An import's notes and the links between them. A link whose target is no note in the vault has `to: null`\n * and keeps its `target`, so a client can draw it as an unresolved node, as Obsidian does.\n */\nexport const NoteGraph = z\n .object({\n notes: z.array(z.object({ id: z.string(), path: z.string(), title: z.string(), tags: z.array(z.string()) }).strict()),\n links: z.array(z.object({ from: z.string(), to: z.string().nullable(), target: z.string(), kind: z.enum([\"link\", \"embed\"]) }).strict()),\n })\n .strict();\nexport type NoteGraph = z.infer<typeof NoteGraph>;\n", "import { z } from \"zod\";\nimport { artifactMathInput, checkMathText } from \"./artifact-math-input.js\";\nimport { AlgorithmTraceSpec } from \"./algorithm-trace.js\";\nimport { PlacementAnswer, PlacementGrade, PlacementQuestionPublic, PlacementQuestionSpec } from \"./course.js\";\nimport { GraphSpec } from \"./graph.js\";\nimport { MultipleChoiceAnswer, MultipleChoiceGrade, MultipleChoicePublic, MultipleChoiceSpec } from \"./multiple-choice.js\";\nimport { SetDiagramSpec } from \"./set-diagram.js\";\nimport { TableSpec } from \"./table.js\";\nimport { WorkedStepsSpec } from \"./worked-steps.js\";\n\nexport * from \"./artifact-math-input.js\";\nexport * from \"./math-text.js\";\nexport * from \"./algorithm-trace.js\";\nexport * from \"./course.js\";\nexport * from \"./lesson.js\";\nexport * from \"./graph.js\";\nexport * from \"./multiple-choice.js\";\nexport * from \"./set-diagram.js\";\nexport * from \"./table.js\";\nexport * from \"./worked-steps.js\";\n\n/**\n * Every artifact kind the agent can produce, one tool per kind (ADR-006).\n * `input` adds current authoring checks to the stored `spec` schema, so old artifacts stay readable.\n * Bump `version` and keep the old schema when a spec changes incompatibly; stored artifacts record\n * the version they were created with.\n */\nexport const artifactKinds = {\n algorithm_trace: {\n version: 1,\n toolName: \"show_algorithm_trace\",\n description:\n \"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.\",\n spec: AlgorithmTraceSpec,\n input: artifactMathInput(AlgorithmTraceSpec, [\"title\", \"steps.*.explanation\"]),\n },\n graph: {\n version: 1,\n toolName: \"show_graph\",\n description:\n \"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.\",\n spec: GraphSpec,\n input: artifactMathInput(GraphSpec, [\"title\", \"nodes.*.label\", \"edges.*.label\", \"steps.*.explanation\"], (spec, ctx) => {\n spec.nodes.forEach((node, i) => {\n if (node.label === undefined) checkMathText(node.id, [\"nodes\", i, \"id\"], ctx);\n });\n }),\n },\n multiple_choice: {\n version: 1,\n toolName: \"ask_multiple_choice\",\n description:\n \"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.\",\n spec: MultipleChoiceSpec,\n input: artifactMathInput(MultipleChoiceSpec, [\"question\", \"options.*.text\", \"options.*.feedback\", \"explanation\"]),\n },\n placement_question: {\n version: 1,\n toolName: \"ask_placement_question\",\n description:\n \"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.\",\n spec: PlacementQuestionSpec,\n input: artifactMathInput(PlacementQuestionSpec, [\"question\", \"options.*.text\", \"explanation\"]),\n },\n set_diagram: {\n version: 1,\n toolName: \"show_set_diagram\",\n description:\n \"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.\",\n spec: SetDiagramSpec,\n input: artifactMathInput(SetDiagramSpec, [\"title\", \"universe\", \"sets.*.label\", \"regions.*.elements.*\", \"steps.*.explanation\", \"steps.*.variables.*.name\", \"steps.*.variables.*.value\"]),\n },\n table: {\n version: 1,\n toolName: \"show_table\",\n description:\n \"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.\",\n spec: TableSpec,\n input: artifactMathInput(TableSpec, [\"title\", \"columns.*\", \"rowHeaders.*\", \"rows.*.*\", \"steps.*.explanation\", \"steps.*.cells.*.value\"]),\n },\n worked_steps: {\n version: 1,\n toolName: \"show_worked_steps\",\n description:\n \"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.\",\n spec: WorkedStepsSpec,\n input: artifactMathInput(WorkedStepsSpec, [\"title\", \"goal\", \"steps.*.label\", \"steps.*.statement\", \"steps.*.justification\"]),\n },\n} as const;\n\nexport type ArtifactKind = keyof typeof artifactKinds;\nexport const ArtifactKind = z.enum(Object.keys(artifactKinds) as [ArtifactKind, ...ArtifactKind[]]);\n\n/** Finds the kind registered for a tool name, if any. */\nexport function kindForTool(toolName: string): ArtifactKind | undefined {\n return (Object.keys(artifactKinds) as ArtifactKind[]).find((kind) => artifactKinds[kind].toolName === toolName);\n}\n\nconst ArtifactBase = { id: z.string(), createdAt: z.string().datetime() };\n\nexport const MultipleChoiceAttempt = z\n .object({ answer: MultipleChoiceAnswer, grade: MultipleChoiceGrade, createdAt: z.string().datetime() })\n .strict();\nexport type MultipleChoiceAttempt = z.infer<typeof MultipleChoiceAttempt>;\n\nexport const PlacementAttempt = z.object({ answer: PlacementAnswer, grade: PlacementGrade, createdAt: z.string().datetime() }).strict();\nexport type PlacementAttempt = z.infer<typeof PlacementAttempt>;\n\n/**\n * An artifact as the client receives it. Checks expose only their public view until answered;\n * after an attempt, the grade (with the correct answer and explanation) is included.\n */\nexport const ArtifactView = z.discriminatedUnion(\"kind\", [\n z\n .object({ ...ArtifactBase, kind: z.literal(\"algorithm_trace\"), version: z.literal(1), spec: AlgorithmTraceSpec })\n .strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"graph\"), version: z.literal(1), spec: GraphSpec }).strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"multiple_choice\"),\n version: z.literal(1),\n spec: MultipleChoicePublic,\n latestAttempt: MultipleChoiceAttempt.optional(),\n })\n .strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"placement_question\"),\n version: z.literal(1),\n spec: PlacementQuestionPublic,\n latestAttempt: PlacementAttempt.optional(),\n })\n .strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"set_diagram\"), version: z.literal(1), spec: SetDiagramSpec }).strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"table\"), version: z.literal(1), spec: TableSpec }).strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"worked_steps\"), version: z.literal(1), spec: WorkedStepsSpec }).strict(),\n]);\nexport type ArtifactView = z.infer<typeof ArtifactView>;\n\nexport * from \"./memory.js\";\nexport * from \"./document.js\";\nexport * from \"./vault.js\";\n\n/** ChatGPT's page for the learner's plan usage and per-app limits (ADR-015). */\nexport const CHATGPT_USAGE_URL = \"https://chatgpt.com/settings/usage\";\n/**\n * The reply error when the learner's ChatGPT plan has hit a usage limit. The UI recognises it and offers\n * \"Manage usage\", as OpenAI's guidelines ask (ADR-015).\n */\nexport const CHATGPT_USAGE_LIMIT_ERROR = \"ChatGPT usage limit reached. Review your plan or this app's limit in ChatGPT settings.\";\n", "import { z } from \"zod\";\nimport { splitMath } from \"./math-text.js\";\n\nconst 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 \u2216, or describe them in words; backticks do not escape artifact math. Correct the affected field and retry this tool call.`;\n\n// Single-letter code escapes stay literal; longer literals such as C:\\Users are still rejected.\nexport function checkMathText(value: unknown, path: (string | number)[], ctx: z.RefinementCtx) {\n if (typeof value === \"string\" && splitMath(value).some((piece) => \"text\" in piece && /\\\\[a-zA-Z]{2,}/.test(piece.text))) {\n ctx.addIssue({ code: \"custom\", path, message: REPAIR });\n }\n}\n\n/** Input-only refinements: stored v1 specs and public views must continue to accept old text. */\nexport function artifactMathInput<T extends z.ZodType>(schema: T, fields: string[], extra?: (spec: z.output<T>, ctx: z.RefinementCtx) => void) {\n return schema.superRefine((spec, ctx) => {\n const visit = (value: unknown, parts: string[], path: (string | number)[]) => {\n if (parts.length === 0) return checkMathText(value, path, ctx);\n const [key, ...rest] = parts;\n if (key === \"*\" && Array.isArray(value)) value.forEach((item, i) => visit(item, rest, [...path, i]));\n else if (value && typeof value === \"object\" && key !== undefined) visit((value as Record<string, unknown>)[key], rest, [...path, key]);\n };\n for (const field of fields) visit(spec, field.split(\".\"), []);\n extra?.(spec, ctx);\n });\n}\n", "const isSpace = (char: string | undefined) => char !== undefined && /\\s/.test(char);\nconst isDigit = (char: string | undefined) => char !== undefined && char >= \"0\" && char <= \"9\";\n\nexport type MathPiece = { text: string } | { formula: string };\n\n/** For math mode: everything is literal except `$...$` formulas, and `\\$`, which is a literal dollar. */\nexport function splitMath(source: string): MathPiece[] {\n const pieces: MathPiece[] = [];\n let literal = \"\";\n let i = 0;\n while (i < source.length) {\n const char = source[i]!;\n if (char === \"\\\\\" && source[i + 1] === \"$\") {\n literal += \"$\";\n i += 2;\n } else if (char !== \"$\") {\n literal += char;\n i += 1;\n } else if (source[i + 1] === \"$\") {\n // A dollar next to another is never a delimiter here, so \"$$x$$\" stays as written.\n while (source[i] === \"$\") {\n literal += \"$\";\n i += 1;\n }\n } else {\n const close = closingDollar(source, i);\n if (close === undefined) {\n literal += \"$\";\n i += 1;\n } else {\n if (literal) pieces.push({ text: literal });\n literal = \"\";\n pieces.push({ formula: source.slice(i + 1, close) });\n i = close + 1;\n }\n }\n }\n if (literal) pieces.push({ text: literal });\n return pieces;\n}\n\nfunction closingDollar(source: string, open: number): number | undefined {\n let close = open + 1;\n while (close < source.length && source[close] !== \"$\") {\n close += source[close] === \"\\\\\" && (source[close + 1] === \"$\" || source[close + 1] === \"\\\\\") ? 2 : 1;\n }\n if (close >= source.length || close === open + 1 || source[close + 1] === \"$\") return undefined;\n if (isSpace(source[open + 1]) || isSpace(source[close - 1]) || isDigit(source[close + 1])) return undefined;\n return /`|\\n\\s*\\n/.test(source.slice(open, close)) ? undefined : close;\n}\n", "import { z } from \"zod\";\n\n/**\n * algorithm_trace v1: a step-through view of an algorithm running over a sequence.\n * Each step can move labelled pointers, highlight index ranges, update variables and\n * replace the sequence (for swaps/sorts). Covers sliding window, two pointers, binary\n * search and simple sorts.\n *\n * State rules (renderers must follow them):\n * - `values` persists: a step without `values` shows the previous step's sequence.\n * - `pointers`, `ranges` and `variables` do not persist: each step lists all of its own,\n * and omitting one means that step has none. So every step is fully described by itself\n * plus the current sequence, and bounds can be checked step by step.\n */\n\nconst MAX_VALUES = 64;\nconst MAX_STEPS = 200;\n\nconst Label = z.string().trim().min(1).max(40);\nconst Cell = z.union([z.number(), z.string().max(24)]);\nconst Index = z.number().int().nonnegative();\n\nexport const TracePointer = z\n .object({\n name: Label.describe('Pointer label shown under the cell, e.g. \"left\", \"right\", \"mid\", \"i\".'),\n index: Index.describe(\"0-based index into the sequence as it is at this step.\"),\n })\n .strict();\n\nexport const TraceRange = z\n .object({\n start: Index.describe(\"0-based start index, inclusive, within the sequence as it is at this step.\"),\n end: Index.describe(\"0-based end index, inclusive. Must be >= start and within the sequence.\"),\n label: Label.optional().describe('Optional label, e.g. \"window\".'),\n tone: z\n .enum([\"active\", \"done\", \"muted\"])\n .optional()\n .describe(\"active = current focus, done = finished/sorted, muted = ruled out. Defaults to active.\"),\n })\n .strict();\n\nexport const TraceVariable = z\n .object({\n name: Label,\n value: z.union([z.number(), z.string().max(80), z.boolean()]),\n })\n .strict();\n\nexport const TraceStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n values: z\n .array(Cell)\n .min(1)\n .max(MAX_VALUES)\n .optional()\n .describe(\"The whole sequence after this step. Omit unless the values changed (e.g. a swap); omitted means unchanged.\"),\n pointers: z\n .array(TracePointer)\n .max(8)\n .optional()\n .describe(\"All pointers to show at this step. Not carried over from earlier steps: repeat any that still apply.\"),\n ranges: z\n .array(TraceRange)\n .max(8)\n .optional()\n .describe(\"All highlighted ranges at this step. Not carried over from earlier steps.\"),\n variables: z\n .array(TraceVariable)\n .max(12)\n .optional()\n .describe(\"All running state at this step, e.g. current sum, best so far. Not carried over from earlier steps.\"),\n })\n .strict();\n\nexport const AlgorithmTraceSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n values: z.array(Cell).min(1).max(MAX_VALUES).describe(\"The input sequence before the first step.\"),\n steps: z.array(TraceStep).min(1).max(MAX_STEPS),\n })\n .strict()\n .superRefine((spec, ctx) => {\n // Every pointer and range must point inside the sequence as it is at that step.\n let length = spec.values.length;\n spec.steps.forEach((step, i) => {\n if (step.values) length = step.values.length;\n step.pointers?.forEach((p, j) => {\n if (p.index >= length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", i, \"pointers\", j, \"index\"],\n message: `index ${p.index} is outside the sequence (length ${length})`,\n });\n }\n });\n step.ranges?.forEach((r, j) => {\n if (r.end >= length || r.start > r.end) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", i, \"ranges\", j],\n message: `range ${r.start}..${r.end} is invalid for a sequence of length ${length}`,\n });\n }\n });\n });\n });\n\nexport type AlgorithmTraceSpec = z.infer<typeof AlgorithmTraceSpec>;\nexport type TraceStep = z.infer<typeof TraceStep>;\n", "import { z } from \"zod\";\nimport { TraceVariable } from \"./algorithm-trace.js\";\n\n/**\n * graph v1: nodes and edges, optionally with steps that walk an algorithm over them. Covers BFS, DFS,\n * shortest paths, spanning trees and tree traversals. Self-loops and parallel edges are allowed and\n * drawn, because a multigraph is ordinary discrete maths. The model never picks coordinates: the\n * renderer computes one layout per graph, so nothing moves between steps.\n *\n * State rules (renderers must follow them):\n * - The graph itself never changes between steps.\n * - `nodeStates`, `edgeStates` and `variables` do not persist: each step lists all of its own, and\n * omitting one means that step has none. So every step is fully described by itself.\n */\n\nconst MAX_NODES = 60;\nconst MAX_EDGES = 200;\nconst MAX_STEPS = 200;\n\nconst Id = z.string().trim().min(1).max(24);\nconst Text = z.string().trim().min(1).max(24);\n\nexport const GraphTone = z.enum([\"active\", \"done\", \"muted\"]);\nexport type GraphTone = z.infer<typeof GraphTone>;\n\nconst ToneField = GraphTone.optional().describe(\n \"active = current focus, done = finished/visited, muted = ruled out. Defaults to active.\",\n);\n\nexport const GraphNode = z\n .object({\n id: Id.describe(\"Unique id, used by edges and steps. Shown on the node if it has no label.\"),\n label: Text.optional().describe(\"Short text on the node. Only $...$ is a formula, e.g. $v_1$.\"),\n })\n .strict();\n\nexport const GraphEdge = z\n .object({\n from: Id.describe(\"Id of a node. In a tree, the parent.\"),\n to: Id.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`.\"),\n side: z\n .enum([\"left\", \"right\"])\n .optional()\n .describe(\n \"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.\",\n ),\n weight: z.number().optional().describe(\"Numeric weight shown on the edge. Give a weight or a label, not both.\"),\n label: Text.optional().describe(\"Text shown on the edge. Only $...$ is a formula.\"),\n })\n .strict();\n\nexport const GraphNodeState = z\n .object({ id: Id.describe(\"Id of a node.\"), tone: ToneField })\n .strict();\n\nexport const GraphEdgeState = z\n .object({\n from: Id,\n to: Id,\n nth: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe(\"Only for parallel edges, and then required: which of the edges joining these nodes, 0-based in the order of `edges`.\"),\n tone: ToneField,\n })\n .strict()\n .describe(\"An edge of the graph. In an undirected graph, from and to may be in either order.\");\n\nexport const GraphStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n nodeStates: z\n .array(GraphNodeState)\n .max(MAX_NODES)\n .optional()\n .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.\"),\n edgeStates: z\n .array(GraphEdgeState)\n .max(MAX_EDGES)\n .optional()\n .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.\"),\n variables: z\n .array(TraceVariable)\n .max(12)\n .optional()\n .describe(\"All running state at this step, e.g. the queue or current distances. Not carried over from earlier steps.\"),\n })\n .strict();\n\nconst pairKey = (from: string, to: string, directed: boolean) =>\n JSON.stringify(directed || from <= to ? [from, to] : [to, from]);\n\n/**\n * Finds which edge a step's edge state refers to, shared by the schema and renderers so they can't\n * disagree. Returns the index into `edges`, or why there isn't one.\n */\nexport function graphEdgeLookup(spec: { directed: boolean; edges: readonly { from: string; to: string }[] }) {\n const byPair = new Map<string, number[]>();\n spec.edges.forEach((edge, i) => {\n const key = pairKey(edge.from, edge.to, spec.directed);\n const indices = byPair.get(key);\n if (indices) indices.push(i);\n else byPair.set(key, [i]);\n });\n return (ref: { from: string; to: string; nth?: number | undefined }): { index: number } | { error: string } => {\n const name = `${ref.from} ${spec.directed ? \"->\" : \"--\"} ${ref.to}`;\n const indices = byPair.get(pairKey(ref.from, ref.to, spec.directed));\n if (!indices) return { error: `there is no edge ${name}` };\n if (ref.nth === undefined && indices.length > 1) return { error: `${indices.length} edges match ${name}: set nth to pick one` };\n const index = indices[ref.nth ?? 0];\n return index === undefined ? { error: `nth ${ref.nth} is out of range: ${indices.length} edges match ${name}` } : { index };\n };\n}\n\n/**\n * Each node's children in edge order, if the graph is a real tree: one root, connected, no cycles. Shared by\n * the schema and renderers so they can't disagree. Every edge must join nodes that exist.\n */\nexport function graphTreeShape(spec: {\n directed: boolean;\n nodes: readonly { id: string }[];\n edges: readonly { from: string; to: string }[];\n}): { root: string; children: Map<string, string[]> } | undefined {\n if (spec.edges.length !== spec.nodes.length - 1) return undefined;\n const ids = spec.nodes.map((node) => node.id);\n const adjacent = new Map<string, string[]>(ids.map((id) => [id, []]));\n for (const { from, to } of spec.edges) {\n adjacent.get(from)!.push(to);\n if (!spec.directed && from !== to) adjacent.get(to)!.push(from);\n }\n const roots = spec.directed ? ids.filter((id) => !spec.edges.some((edge) => edge.to === id)) : ids.slice(0, 1);\n const root = roots[0];\n if (roots.length !== 1 || root === undefined) return undefined;\n\n const children = new Map<string, string[]>();\n const pending = [root];\n while (pending.length) {\n const id = pending.pop()!;\n const next = adjacent.get(id)!.filter((other) => !children.has(other));\n children.set(id, next);\n pending.push(...next);\n }\n // With n - 1 edges, reaching all n nodes means there can't be a cycle.\n return children.size === ids.length ? { root, children } : undefined;\n}\n\n/** The rules for `side`, which only says anything about a tree that really gets drawn as one. */\nfunction checkSides(spec: Pick<GraphSpec, \"kind\" | \"directed\" | \"nodes\" | \"edges\">, ctx: z.RefinementCtx) {\n const sided = spec.edges.flatMap((edge, i) => (edge.side ? [{ edge, side: edge.side, path: [\"edges\", i, \"side\"] }] : []));\n const first = sided[0];\n if (!first) return;\n if (spec.kind !== \"tree\") {\n for (const { path } of sided) ctx.addIssue({ code: \"custom\", path, message: 'side only applies when kind is \"tree\": remove it, or set kind' });\n return;\n }\n const shape = graphTreeShape(spec);\n if (!shape) {\n 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\" });\n return;\n }\n const sideOf = new Map<string, \"left\" | \"right\">();\n for (const { edge, side, path } of sided) {\n if (shape.children.get(edge.from)!.includes(edge.to)) sideOf.set(edge.to, side);\n 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` });\n }\n for (const [parent, children] of shape.children) {\n const sides = children.flatMap((child) => sideOf.get(child) ?? []);\n if (sides.length > 0 && sides.length < children.length) {\n ctx.addIssue({ code: \"custom\", path: [\"edges\"], message: `node ${parent} mixes children with and without a side: give all of them one, or none` });\n }\n for (const side of [\"left\", \"right\"] as const) {\n if (sides.filter((s) => s === side).length > 1) ctx.addIssue({ code: \"custom\", path: [\"edges\"], message: `node ${parent} has two ${side} children` });\n }\n }\n}\n\nexport const GraphSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n directed: z.boolean().describe(\"True draws arrowheads from `from` to `to`.\"),\n kind: z\n .enum([\"tree\", \"graph\"])\n .optional()\n .describe(\n \"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.\",\n ),\n nodes: z.array(GraphNode).min(1).max(MAX_NODES),\n edges: z.array(GraphEdge).max(MAX_EDGES).describe(\"Self-loops and parallel edges are allowed.\"),\n steps: z.array(GraphStep).min(1).max(MAX_STEPS).optional().describe(\"Omit to show the graph without stepping through it.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const ids = new Set<string>();\n spec.nodes.forEach((node, i) => {\n if (ids.has(node.id)) ctx.addIssue({ code: \"custom\", path: [\"nodes\", i, \"id\"], message: `duplicate node id ${node.id}` });\n ids.add(node.id);\n });\n spec.edges.forEach((edge, i) => {\n for (const end of [\"from\", \"to\"] as const) {\n if (!ids.has(edge[end])) ctx.addIssue({ code: \"custom\", path: [\"edges\", i, end], message: `no node has id ${edge[end]}` });\n }\n if (edge.weight !== undefined && edge.label !== undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"edges\", i], message: \"give a weight or a label, not both\" });\n }\n });\n if (spec.edges.every((edge) => ids.has(edge.from) && ids.has(edge.to))) checkSides(spec, ctx);\n const lookup = graphEdgeLookup(spec);\n spec.steps?.forEach((step, i) => {\n const seenNodes = new Set<string>();\n step.nodeStates?.forEach((state, j) => {\n const path = [\"steps\", i, \"nodeStates\", j];\n if (!ids.has(state.id)) ctx.addIssue({ code: \"custom\", path, message: `no node has id ${state.id}` });\n if (seenNodes.has(state.id)) ctx.addIssue({ code: \"custom\", path, message: `node ${state.id} has two states in one step` });\n seenNodes.add(state.id);\n });\n const seenEdges = new Set<number>();\n step.edgeStates?.forEach((state, j) => {\n const path = [\"steps\", i, \"edgeStates\", j];\n const found = lookup(state);\n if (\"error\" in found) return ctx.addIssue({ code: \"custom\", path, message: found.error });\n if (seenEdges.has(found.index)) ctx.addIssue({ code: \"custom\", path, message: `edge ${found.index} has two states in one step` });\n seenEdges.add(found.index);\n });\n });\n });\n\nexport type GraphSpec = z.infer<typeof GraphSpec>;\nexport type GraphStep = z.infer<typeof GraphStep>;\n", "import { z } from \"zod\";\n\n/**\n * multiple_choice v1: a comprehension check with exactly one correct option, graded by the\n * server without a model call (ADR-006). The full spec (with the answer) stays on the server;\n * the client gets the public view until the learner has answered.\n */\n\nexport const MultipleChoiceOption = z\n .object({\n text: z.string().trim().min(1).max(300),\n feedback: z\n .string()\n .trim()\n .min(1)\n .max(500)\n .optional()\n .describe(\"Shown if the learner picks this option: why it is right or what misconception it reflects.\"),\n })\n .strict();\n\nexport const MultipleChoiceSpec = z\n .object({\n concept: z\n .string()\n .trim()\n .min(1)\n .max(80)\n .describe('Short label for the concept being checked, e.g. \"sliding window invariant\". Used to track progress.'),\n question: z.string().trim().min(1).max(1000),\n options: z.array(MultipleChoiceOption).min(2).max(6).describe(\"2-6 options with distinct text.\"),\n correctOptionIndex: z\n .number()\n .int()\n .nonnegative()\n .describe(\"0-based index of the single correct option; must be less than the number of options.\"),\n explanation: z.string().trim().min(1).max(1000).describe(\"Shown after answering: why the correct option is correct.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n if (spec.correctOptionIndex >= spec.options.length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"correctOptionIndex\"],\n message: \"correctOptionIndex must point at one of the options\",\n });\n }\n // Two identical options can't be told apart, but only one would be graded correct. Compare the\n // trimmed text exactly: case and inner spacing can be the point of a question (\"A\" vs \"a\",\n // \"a b\" vs \"a b\"). NFC only merges Unicode spellings that render identically.\n const seen = new Map<string, number>();\n spec.options.forEach((option, i) => {\n const key = option.text.normalize(\"NFC\");\n const first = seen.get(key);\n if (first !== undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: `duplicates option ${first}` });\n } else {\n seen.set(key, i);\n }\n });\n });\n\nexport type MultipleChoiceSpec = z.infer<typeof MultipleChoiceSpec>;\n\n/** What the client sees before answering: no answer key, no feedback. */\nexport const MultipleChoicePublic = z\n .object({\n concept: z.string(),\n question: z.string(),\n options: z.array(z.object({ text: z.string() }).strict()),\n })\n .strict();\n\nexport type MultipleChoicePublic = z.infer<typeof MultipleChoicePublic>;\n\nexport function toMultipleChoicePublic(spec: MultipleChoiceSpec): MultipleChoicePublic {\n return {\n concept: spec.concept,\n question: spec.question,\n options: spec.options.map((o) => ({ text: o.text })),\n };\n}\n\nexport const MultipleChoiceAnswer = z.object({ optionIndex: z.number().int().nonnegative() }).strict();\nexport type MultipleChoiceAnswer = z.infer<typeof MultipleChoiceAnswer>;\n\nexport const MultipleChoiceGrade = z\n .object({\n correct: z.boolean(),\n correctOptionIndex: z.number().int().nonnegative(),\n explanation: z.string(),\n feedback: z.string().optional(),\n })\n .strict();\nexport type MultipleChoiceGrade = z.infer<typeof MultipleChoiceGrade>;\n\n/** Deterministic grader. Throws if the answer points outside the options. */\nexport function gradeMultipleChoice(spec: MultipleChoiceSpec, answer: MultipleChoiceAnswer): MultipleChoiceGrade {\n const chosen = spec.options[answer.optionIndex];\n if (!chosen) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);\n return {\n correct: answer.optionIndex === spec.correctOptionIndex,\n correctOptionIndex: spec.correctOptionIndex,\n explanation: spec.explanation,\n ...(chosen.feedback ? { feedback: chosen.feedback } : {}),\n };\n}\n", "import { z } from \"zod\";\nimport { TraceVariable } from \"./algorithm-trace.js\";\n\n/**\n * set_diagram v1: a Venn diagram of up to 3 sets, with what each region contains and optional steps\n * that highlight regions. Covers union, intersection, complement, difference and inclusion-exclusion.\n *\n * A region is named by the set ids it is inside and is outside every other set, so with sets a, b and c,\n * `[\"a\", \"b\"]` is \"in a and b, not c\", and `[\"b\", \"a\"]` is the same region. `[]` is outside every set.\n * A region that isn't listed has no contents shown; a listed region with no elements and no count is empty.\n *\n * Highlights and variables do not persist: each step lists all of its own.\n */\n\nconst MAX_SETS = 3;\n/** 2^3: every region of a 3-set diagram, including outside. */\nconst MAX_REGIONS = 8;\nconst MAX_ELEMENTS = 30;\nconst MAX_STEPS = 40;\n\nconst SetId = z.string().trim().min(1).max(24);\n/** Text drawn in a tight spot in the diagram, so it stays on one line. */\nconst ONE_LINE = /^[^\\n\\r\\v\\f\\u0085\\u2028\\u2029]*$/;\nconst oneLine = (max: number) => z.string().trim().min(1).max(max).regex(ONE_LINE, \"must not contain line breaks\");\nconst Element = z.union([z.number(), oneLine(24)]);\n\n/** The same string for any ordering of the same set ids, so a region can be compared and looked up. */\nexport function setRegionKey(ids: readonly string[]): string {\n return JSON.stringify([...ids].sort());\n}\n\nconst RegionIn = z.array(SetId).max(MAX_SETS);\n\nexport const SetDiagramSet = z\n .object({\n id: SetId.describe('Short id used to refer to this set, e.g. \"a\". Unique within the diagram.'),\n label: oneLine(32).describe('Shown next to the circle, e.g. \"$A$\" or \"Multiples of 3\", on one line. Only $...$ is a formula.'),\n })\n .strict();\n\nexport const SetDiagramRegion = z\n .object({\n 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.'),\n elements: z.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.\"),\n count: z\n .number()\n .int()\n .nonnegative()\n .max(1_000_000)\n .optional()\n .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.\"),\n })\n .strict();\n\nexport const SetDiagramHighlight = z\n .object({\n 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.\"),\n tone: z.enum([\"active\", \"done\", \"muted\"]).optional().describe(\"active = current focus, done = finished, muted = ruled out. Defaults to active.\"),\n })\n .strict();\n\nexport const SetDiagramStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What this step shows, in one or two sentences.\"),\n highlights: z\n .array(SetDiagramHighlight)\n .max(MAX_REGIONS)\n .optional()\n .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.\"),\n variables: z.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.\"),\n })\n .strict();\n\nexport const SetDiagramSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n sets: z.array(SetDiagramSet).min(1).max(MAX_SETS).describe(\"The circles, 1 to 3.\"),\n 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.'),\n regions: z.array(SetDiagramRegion).max(MAX_REGIONS).describe(\"What each region contains, each region at most once.\"),\n steps: z.array(SetDiagramStep).min(1).max(MAX_STEPS).optional().describe(\"Optional walk through the diagram. Omit for a static diagram.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const ids = spec.sets.map((s) => s.id);\n spec.sets.forEach((set, i) => {\n if (ids.indexOf(set.id) !== i) ctx.addIssue({ code: \"custom\", path: [\"sets\", i, \"id\"], message: `duplicate set id \"${set.id}\"` });\n });\n\n /** Checks a list of region references, and reports any region named twice, whatever the order of its ids. */\n const checkRegions = (entries: readonly { in: string[] }[], path: (string | number)[]) => {\n const seen = new Set<string>();\n entries.forEach((entry, i) => {\n const at = [...path, i, \"in\"];\n entry.in.forEach((id, j) => {\n if (!ids.includes(id)) ctx.addIssue({ code: \"custom\", path: [...at, j], message: `unknown set \"${id}\"` });\n if (entry.in.indexOf(id) !== j) ctx.addIssue({ code: \"custom\", path: [...at, j], message: `set \"${id}\" is named twice` });\n });\n if (entry.in.length === 0 && spec.universe === undefined) {\n ctx.addIssue({ code: \"custom\", path: at, message: \"the region outside every set needs `universe`\" });\n }\n const key = setRegionKey(entry.in);\n if (seen.has(key)) ctx.addIssue({ code: \"custom\", path: at, message: `region ${key} appears more than once` });\n seen.add(key);\n });\n };\n checkRegions(spec.regions, [\"regions\"]);\n spec.steps?.forEach((step, i) => checkRegions(step.highlights ?? [], [\"steps\", i, \"highlights\"]));\n\n // Regions don't overlap, so an element in two of them would teach something false.\n const placed = new Set<string>();\n spec.regions.forEach((region, i) => {\n region.elements.forEach((element, j) => {\n if (placed.has(String(element))) {\n ctx.addIssue({ code: \"custom\", path: [\"regions\", i, \"elements\", j], message: `element \"${element}\" appears more than once; regions don't overlap` });\n }\n placed.add(String(element));\n });\n if (region.count !== undefined && region.count < region.elements.length) {\n ctx.addIssue({ code: \"custom\", path: [\"regions\", i, \"count\"], message: `count ${region.count} is less than the ${region.elements.length} elements listed` });\n }\n });\n });\n\nexport type SetDiagramSpec = z.infer<typeof SetDiagramSpec>;\nexport type SetDiagramStep = z.infer<typeof SetDiagramStep>;\nexport type SetDiagramHighlight = z.infer<typeof SetDiagramHighlight>;\n", "import { z } from \"zod\";\n\n/**\n * table v1: a truth table, relation matrix or other tabular working, optionally stepped through.\n *\n * State rules (renderers must follow them):\n * - `cells` persists: a changed cell keeps its new value on every later step.\n * - `highlight` does not persist: each step lists all of its own, and omitting it means that step has none.\n * The table's shape never changes, so every index can be checked against `rows` and `columns`.\n */\n\nconst MAX_COLUMNS = 16;\nconst MAX_ROWS = 64;\nconst MAX_STEPS = 100;\n\nconst Header = z.string().trim().min(1).max(80);\nconst CellValue = z.union([z.number(), z.boolean(), z.string().max(120)]);\nconst Index = z.number().int().nonnegative();\n\nexport const TableHighlight = z\n .object({\n row: Index.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.\"),\n column: Index.optional().describe(\"0-based data column, below the number of columns. With no row, highlights the whole column. With both, highlights one cell.\"),\n tone: z\n .enum([\"active\", \"done\", \"muted\"])\n .optional()\n .describe(\"active = current focus, done = finished, muted = ruled out. Defaults to active. Where highlights overlap, the later one wins.\"),\n })\n .strict();\n\nexport const TableCellChange = z\n .object({\n row: Index.describe(\"0-based data row, below the number of rows.\"),\n column: Index.describe(\"0-based data column, below the number of columns.\"),\n value: CellValue.describe(\"The cell's value from this step on.\"),\n })\n .strict();\n\nexport const TableStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n highlight: z\n .array(TableHighlight)\n .max(32)\n .optional()\n .describe(\"All cells, rows and columns to highlight at this step. Not carried over from earlier steps.\"),\n cells: z\n .array(TableCellChange)\n .max(64)\n .optional()\n .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.'),\n })\n .strict();\n\nexport const TableSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n columns: z.array(Header).min(1).max(MAX_COLUMNS).describe(\"Column headers, one per data column. Don't include a header for rowHeaders.\"),\n rows: z\n .array(z.array(CellValue).min(1).max(MAX_COLUMNS))\n .min(1)\n .max(MAX_ROWS)\n .describe('Data rows, each with exactly one cell per column. A boolean shows as T or F; \"\" is a blank cell.'),\n rowHeaders: z.array(Header).max(MAX_ROWS).optional().describe(\"Optional label for each row, e.g. a relation matrix's elements. Exactly one per row.\"),\n steps: z.array(TableStep).min(1).max(MAX_STEPS).optional().describe(\"Omit for a static table. With steps, the learner steps through them.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const rowCount = spec.rows.length;\n const columnCount = spec.columns.length;\n spec.rows.forEach((row, i) => {\n if (row.length !== columnCount) {\n ctx.addIssue({ code: \"custom\", path: [\"rows\", i], message: `row has ${row.length} cells but there are ${columnCount} columns` });\n }\n });\n if (spec.rowHeaders && spec.rowHeaders.length !== rowCount) {\n ctx.addIssue({ code: \"custom\", path: [\"rowHeaders\"], message: `${spec.rowHeaders.length} row headers for ${rowCount} rows` });\n }\n const checkRow = (row: number, path: (string | number)[]) => {\n if (row >= rowCount) ctx.addIssue({ code: \"custom\", path, message: `row ${row} is outside the table (${rowCount} rows)` });\n };\n const checkColumn = (column: number, path: (string | number)[]) => {\n if (column >= columnCount) ctx.addIssue({ code: \"custom\", path, message: `column ${column} is outside the table (${columnCount} columns)` });\n };\n spec.steps?.forEach((step, i) => {\n step.highlight?.forEach((h, j) => {\n const path = [\"steps\", i, \"highlight\", j];\n if (h.row === undefined && h.column === undefined) ctx.addIssue({ code: \"custom\", path, message: \"a highlight needs a row, a column or both\" });\n if (h.row !== undefined) checkRow(h.row, [...path, \"row\"]);\n if (h.column !== undefined) checkColumn(h.column, [...path, \"column\"]);\n });\n step.cells?.forEach((c, j) => {\n checkRow(c.row, [\"steps\", i, \"cells\", j, \"row\"]);\n checkColumn(c.column, [\"steps\", i, \"cells\", j, \"column\"]);\n });\n });\n });\n\nexport type TableSpec = z.infer<typeof TableSpec>;\nexport type TableStep = z.infer<typeof TableStep>;\n", "import { z } from \"zod\";\n\n/**\n * worked_steps v1: a proof, induction or combinatorics working, revealed one step at a time.\n * Every step stays on screen once revealed, so later steps can be read against earlier ones.\n */\n\nconst MAX_STEPS = 50;\n\nexport const WorkedStep = z\n .object({\n label: z.string().trim().min(1).max(40).optional().describe('Optional heading for this part of the working, e.g. \"Base case\", \"Inductive step\".'),\n statement: z\n .string()\n .trim()\n .min(1)\n .max(1000)\n .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.\"),\n justification: z.string().trim().min(1).max(500).describe('Why it follows, e.g. \"by the inductive hypothesis\".'),\n })\n .strict();\n\nexport const WorkedStepsSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n goal: z.string().trim().min(1).max(500).optional().describe(\"Optional statement of what is being shown, e.g. the claim to prove.\"),\n steps: z.array(WorkedStep).min(1).max(MAX_STEPS),\n })\n .strict();\n\nexport type WorkedStepsSpec = z.infer<typeof WorkedStepsSpec>;\nexport type WorkedStep = z.infer<typeof WorkedStep>;\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,SAAS;AAOX,IAAM,iBAAiB;AACvB,IAAM,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,cAAc;AAG9D,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC,EAAE,OAAO;AAGjE,IAAM,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAO5C,IAAM,wBAAwB,EAClC,OAAO;AAAA,EACN,SAAS,YAAY,SAAS,8HAA+H;AAAA,EAC7J,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,GAAI;AAAA,EAC3C,SAAS,EACN,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,CAAC,EAAE,OAAO,CAAC,EACpE,IAAI,CAAC,EACL,IAAI,CAAC,EACL,SAAS,6JAA6J;AAAA,EACzK,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS,6CAA6C;AAAA,EACzG,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS,gFAAgF;AAC1I,CAAC,EACA,OAAO,EACP,YAAY,CAAC,MAAM,QAAQ;AAC1B,MAAI,KAAK,sBAAsB,KAAK,QAAQ,QAAQ;AAClD,QAAI,SAAS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ACG,OAAO;AAAA,IACN,GAAG;AAAA,IACH,MAAMA,IAAE,QAAQ,oBAAoB;AAAA,IACpC,SAASA,IAAE,QAAQ,CAAC;AAAA,IACpB,MAAM;AAAA,IACN,eAAe,iBAAiB,SAAS;AAAA,EAC3C,CAAC,EACA,OAAO;AAAA,EACVA,IAAE,OAAO,EAAE,GAAG,cAAc,MAAMA,IAAE,QAAQ,aAAa,GAAG,SAASA,IAAE,QAAQ,CAAC,GAAG,MAAM,eAAe,CAAC,EAAE,OAAO;AAAA,EAClHA,IAAE,OAAO,EAAE,GAAG,cAAc,MAAMA,IAAE,QAAQ,OAAO,GAAG,SAASA,IAAE,QAAQ,CAAC,GAAG,MAAM,UAAU,CAAC,EAAE,OAAO;AAAA,EACvGA,IAAE,OAAO,EAAE,GAAG,cAAc,MAAMA,IAAE,QAAQ,cAAc,GAAG,SAASA,IAAE,QAAQ,CAAC,GAAG,MAAM,gBAAgB,CAAC,EAAE,OAAO;AACtH,CAAC;AAaM,IAAM,4BAA4B;",
|
|
6
|
+
"names": ["z", "z", "z", "z", "z", "z", "z", "MAX_STEPS", "z", "z", "z", "MAX_STEPS", "z", "z", "MAX_STEPS", "Index", "z", "MAX_STEPS", "z", "z"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// ../server/src/documents/extract.ts
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { getResolvedPDFJS } from "unpdf";
|
|
4
|
+
import yauzl from "yauzl";
|
|
5
|
+
var DocumentError = class extends Error {
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
code;
|
|
11
|
+
};
|
|
12
|
+
var MAX_PAGES = 5e3;
|
|
13
|
+
var MAX_TEXT_CHARS = 1e7;
|
|
14
|
+
var MIN_TEXT_CHARS = 20;
|
|
15
|
+
var MAX_ZIP_ENTRIES = 2e4;
|
|
16
|
+
var MAX_ZIP_DECLARED_BYTES = 1024 * 1024 * 1024;
|
|
17
|
+
var MAX_XML_PART_BYTES = 32 * 1024 * 1024;
|
|
18
|
+
var MAX_XML_TOTAL_BYTES = 256 * 1024 * 1024;
|
|
19
|
+
var WRONG_TYPE = "Only PDF and PowerPoint (.pptx) files can be attached.";
|
|
20
|
+
var CORRUPT = "This file looks damaged and can't be read.";
|
|
21
|
+
var ENCRYPTED = "This file is password-protected. Remove the password and upload it again.";
|
|
22
|
+
var TOO_MUCH_TEXT = "This file has too much text to attach. Try uploading the part you need.";
|
|
23
|
+
function cleanText(text) {
|
|
24
|
+
return text.replace(/[^\P{C}\n\t]/gu, "").replace(/[ff-st\u{1D400}-\u{1D7FF}]/gu, (c) => c.normalize("NFKC")).replace(/[ \t]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
25
|
+
}
|
|
26
|
+
function finish(kind, pageCount, raw) {
|
|
27
|
+
const pages = raw.map(({ page, text }) => ({ page, text: cleanText(text) })).filter((page) => page.text);
|
|
28
|
+
if (pages.reduce((sum, page) => sum + page.text.replace(/\s/g, "").length, 0) < MIN_TEXT_CHARS) {
|
|
29
|
+
throw new DocumentError(
|
|
30
|
+
"no_text",
|
|
31
|
+
kind === "pdf" ? "This PDF has no readable text; it's probably scanned. Mivra can't read images yet, so try a PDF with selectable text." : "These slides have no readable text; they're probably images. Mivra can't read images yet."
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
return { kind, pageCount, pages };
|
|
35
|
+
}
|
|
36
|
+
async function extractPdf(bytes) {
|
|
37
|
+
const { getDocument } = await getResolvedPDFJS();
|
|
38
|
+
const task = getDocument({ data: new Uint8Array(bytes), useSystemFonts: false, disableFontFace: true, verbosity: 0 });
|
|
39
|
+
try {
|
|
40
|
+
const pdf = await task.promise.catch((error) => {
|
|
41
|
+
throw error?.name === "PasswordException" ? new DocumentError("encrypted", ENCRYPTED) : new DocumentError("corrupt", CORRUPT);
|
|
42
|
+
});
|
|
43
|
+
if (pdf.numPages > MAX_PAGES) throw new DocumentError("too_complex", `This PDF has more than ${MAX_PAGES} pages.`);
|
|
44
|
+
const pages = [];
|
|
45
|
+
let chars = 0;
|
|
46
|
+
for (let page = 1; page <= pdf.numPages; page++) {
|
|
47
|
+
const text = await pdf.getPage(page).then(async (handle) => {
|
|
48
|
+
const content = await handle.getTextContent();
|
|
49
|
+
handle.cleanup();
|
|
50
|
+
return content.items.map((item) => "str" in item ? item.str + (item.hasEOL ? "\n" : "") : "").join("");
|
|
51
|
+
}).catch(() => "");
|
|
52
|
+
chars += text.length;
|
|
53
|
+
if (chars > MAX_TEXT_CHARS) throw new DocumentError("too_complex", TOO_MUCH_TEXT);
|
|
54
|
+
pages.push({ page, text });
|
|
55
|
+
}
|
|
56
|
+
return finish("pdf", pdf.numPages, pages);
|
|
57
|
+
} finally {
|
|
58
|
+
await task.destroy().catch(() => {
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function openZip(bytes) {
|
|
63
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
yauzl.fromBuffer(buffer, { lazyEntries: true, strictFileNames: true, validateEntrySizes: true }, (openError, zip) => {
|
|
66
|
+
if (openError) return reject(new DocumentError("corrupt", CORRUPT));
|
|
67
|
+
if (zip.entryCount > MAX_ZIP_ENTRIES) return reject(new DocumentError("too_complex", "This file contains too many parts to read safely."));
|
|
68
|
+
const entries = /* @__PURE__ */ new Map();
|
|
69
|
+
let declared = 0;
|
|
70
|
+
let unpacked = 0;
|
|
71
|
+
zip.on("error", () => reject(new DocumentError("corrupt", CORRUPT)));
|
|
72
|
+
zip.on("entry", (entry) => {
|
|
73
|
+
if (entry.isEncrypted()) return reject(new DocumentError("encrypted", ENCRYPTED));
|
|
74
|
+
declared += entry.uncompressedSize;
|
|
75
|
+
if (declared > MAX_ZIP_DECLARED_BYTES) return reject(new DocumentError("too_complex", "This file unpacks to too much data to read safely."));
|
|
76
|
+
if (entries.has(entry.fileName)) return reject(new DocumentError("corrupt", CORRUPT));
|
|
77
|
+
entries.set(entry.fileName, entry);
|
|
78
|
+
zip.readEntry();
|
|
79
|
+
});
|
|
80
|
+
const read = (name) => new Promise((done, fail) => {
|
|
81
|
+
const entry = entries.get(name);
|
|
82
|
+
if (!entry) return fail(new DocumentError("corrupt", CORRUPT));
|
|
83
|
+
const tooMuch = new DocumentError("too_complex", "This file unpacks to too much data to read safely.");
|
|
84
|
+
if (entry.uncompressedSize > MAX_XML_PART_BYTES) return fail(tooMuch);
|
|
85
|
+
zip.openReadStream(entry, (streamError, stream) => {
|
|
86
|
+
if (streamError) return fail(new DocumentError("corrupt", CORRUPT));
|
|
87
|
+
const chunks = [];
|
|
88
|
+
stream.on("data", (chunk) => {
|
|
89
|
+
unpacked += chunk.length;
|
|
90
|
+
if (unpacked > MAX_XML_TOTAL_BYTES) stream.destroy(tooMuch);
|
|
91
|
+
else chunks.push(chunk);
|
|
92
|
+
});
|
|
93
|
+
stream.on("error", (error) => fail(error instanceof DocumentError ? error : new DocumentError("corrupt", CORRUPT)));
|
|
94
|
+
stream.on("end", () => done(Buffer.concat(chunks)));
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
zip.on("end", () => resolve({ names: new Set(entries.keys()), read, close: () => zip.close() }));
|
|
98
|
+
zip.readEntry();
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function decodeXml(bytes) {
|
|
103
|
+
const [a, b] = bytes;
|
|
104
|
+
const encoding = a === 255 && b === 254 || a === 60 && b === 0 ? "utf-16le" : a === 254 && b === 255 || a === 0 && b === 60 ? "utf-16be" : "utf-8";
|
|
105
|
+
const xml = new TextDecoder(encoding).decode(bytes);
|
|
106
|
+
if (/<!(DOCTYPE|ENTITY)/i.test(xml)) throw new DocumentError("corrupt", "This file contains unsafe XML and can't be read.");
|
|
107
|
+
return xml;
|
|
108
|
+
}
|
|
109
|
+
var NAMED_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
110
|
+
function decodeEntities(text) {
|
|
111
|
+
return text.replace(/&(?:#(\d{1,7})|#x([\da-f]{1,6})|(amp|lt|gt|quot|apos));/gi, (whole, dec, hex, name) => {
|
|
112
|
+
if (name) return NAMED_ENTITIES[name.toLowerCase()] ?? whole;
|
|
113
|
+
const code = dec ? Number(dec) : parseInt(hex, 16);
|
|
114
|
+
return code <= 1114111 ? String.fromCodePoint(code) : whole;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function* xmlTokens(xml) {
|
|
118
|
+
for (const [token] of xml.matchAll(/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[^>]*>|[^<]+/g)) {
|
|
119
|
+
if (token.startsWith("<!--") || token.startsWith("<?")) continue;
|
|
120
|
+
if (token.startsWith("<![CDATA[")) yield { text: token.slice(9, -3) };
|
|
121
|
+
else if (token.startsWith("<")) {
|
|
122
|
+
const name = /^<\/?(?:[\w.-]+:)?([\w.-]+)/.exec(token)?.[1] ?? "";
|
|
123
|
+
yield { tag: token, name, closing: token.startsWith("</"), selfClosing: token.endsWith("/>") };
|
|
124
|
+
} else yield { text: decodeEntities(token) };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function slideText(xml) {
|
|
128
|
+
let out = "";
|
|
129
|
+
let inText = 0;
|
|
130
|
+
let inFallback = 0;
|
|
131
|
+
for (const token of xmlTokens(xml)) {
|
|
132
|
+
if ("text" in token) {
|
|
133
|
+
if (inText > 0 && inFallback === 0) out += token.text;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const delta = token.selfClosing ? 0 : token.closing ? -1 : 1;
|
|
137
|
+
if (token.name === "Fallback") inFallback = Math.max(0, inFallback + delta);
|
|
138
|
+
else if (token.name === "t") inText = Math.max(0, inText + delta);
|
|
139
|
+
else if (inFallback === 0 && (token.name === "br" || token.name === "p" && token.closing)) out += "\n";
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
var attribute = (tag, name) => new RegExp(`\\s${name.source}\\s*=\\s*["']([^"']*)["']`).exec(tag)?.[1];
|
|
144
|
+
function slideOrder(presentationXml, relsXml) {
|
|
145
|
+
const targets = /* @__PURE__ */ new Map();
|
|
146
|
+
for (const token of xmlTokens(relsXml)) {
|
|
147
|
+
if ("tag" in token && token.name === "Relationship" && !token.closing) {
|
|
148
|
+
const id = attribute(token.tag, /Id/);
|
|
149
|
+
const target = attribute(token.tag, /Target/);
|
|
150
|
+
if (id && target) targets.set(id, target);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const slides = [];
|
|
154
|
+
for (const token of xmlTokens(presentationXml)) {
|
|
155
|
+
if ("tag" in token && token.name === "sldId" && !token.closing) {
|
|
156
|
+
const target = targets.get(attribute(token.tag, /[\w.-]+:id/) ?? "");
|
|
157
|
+
const part = target && (target.startsWith("/") ? posix.normalize(target).slice(1) : posix.join("ppt", target));
|
|
158
|
+
slides.push(part && /^ppt\/slides\/[^/]+\.xml$/.test(part) ? part : void 0);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return slides;
|
|
162
|
+
}
|
|
163
|
+
async function extractPptx(bytes) {
|
|
164
|
+
const zip = await openZip(bytes);
|
|
165
|
+
try {
|
|
166
|
+
if (!zip.names.has("[Content_Types].xml")) throw new DocumentError("wrong_type", WRONG_TYPE);
|
|
167
|
+
const types = decodeXml(await zip.read("[Content_Types].xml"));
|
|
168
|
+
if (!/officedocument\.presentationml\.(presentation|slideshow|template)\.main\+xml/i.test(types)) throw new DocumentError("wrong_type", WRONG_TYPE);
|
|
169
|
+
if (!zip.names.has("ppt/presentation.xml") || !zip.names.has("ppt/_rels/presentation.xml.rels")) throw new DocumentError("corrupt", CORRUPT);
|
|
170
|
+
const slides = slideOrder(decodeXml(await zip.read("ppt/presentation.xml")), decodeXml(await zip.read("ppt/_rels/presentation.xml.rels")));
|
|
171
|
+
if (slides.length > MAX_PAGES) throw new DocumentError("too_complex", `This file has more than ${MAX_PAGES} slides.`);
|
|
172
|
+
const pages = [];
|
|
173
|
+
let chars = 0;
|
|
174
|
+
for (const [index, part] of slides.entries()) {
|
|
175
|
+
if (!part || !zip.names.has(part)) continue;
|
|
176
|
+
const text = slideText(decodeXml(await zip.read(part)));
|
|
177
|
+
chars += text.length;
|
|
178
|
+
if (chars > MAX_TEXT_CHARS) throw new DocumentError("too_complex", TOO_MUCH_TEXT);
|
|
179
|
+
pages.push({ page: index + 1, text });
|
|
180
|
+
}
|
|
181
|
+
return finish("pptx", slides.length, pages);
|
|
182
|
+
} finally {
|
|
183
|
+
zip.close();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
var startsWith = (bytes, magic) => magic.every((byte, i) => bytes[i] === byte);
|
|
187
|
+
async function extractDocument(bytes) {
|
|
188
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
189
|
+
if (buffer.subarray(0, 1024).includes("%PDF-")) return extractPdf(bytes);
|
|
190
|
+
if (startsWith(bytes, [80, 75, 3, 4])) return extractPptx(bytes);
|
|
191
|
+
if (startsWith(bytes, [208, 207, 17, 224]) && buffer.includes(Buffer.from("EncryptedPackage", "utf16le"))) throw new DocumentError("encrypted", ENCRYPTED);
|
|
192
|
+
throw new DocumentError("wrong_type", WRONG_TYPE);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ../server/src/notes/vault-path.ts
|
|
196
|
+
function cleanVaultPath(raw) {
|
|
197
|
+
let path = raw.replace(/\\/g, "/").normalize("NFC");
|
|
198
|
+
if (path.includes("\0") || path.startsWith("/") || /^[A-Za-z]:/.test(path)) return { reason: "bad_path" };
|
|
199
|
+
path = path.replace(/^(\.\/)+/, "");
|
|
200
|
+
const segments = path.split("/");
|
|
201
|
+
if (segments.some((s) => s === "" || s === "." || s === "..")) return { reason: "bad_path" };
|
|
202
|
+
if (segments.some((s) => s.startsWith("."))) return { reason: "hidden" };
|
|
203
|
+
if (!/\.md$/i.test(path)) return { reason: "not_markdown" };
|
|
204
|
+
return { path };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export {
|
|
208
|
+
DocumentError,
|
|
209
|
+
extractDocument,
|
|
210
|
+
cleanVaultPath
|
|
211
|
+
};
|
|
212
|
+
//# sourceMappingURL=chunk-KE5ZEREE.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../server/src/documents/extract.ts", "../../server/src/notes/vault-path.ts"],
|
|
4
|
+
"sourcesContent": ["import { posix } from \"node:path\";\nimport { getResolvedPDFJS } from \"unpdf\";\nimport yauzl from \"yauzl\";\n\n/**\n * Text extraction for untrusted PDF and PPTX files (ADR-010). This runs inside a subprocess (see\n * extract-in-child.ts), which supplies the timeout and memory limits this code can't enforce itself.\n */\n\nexport type DocumentErrorCode = \"too_large\" | \"wrong_type\" | \"no_text\" | \"encrypted\" | \"corrupt\" | \"too_complex\" | \"timeout\" | \"failed\";\n\n/** A failure whose message is safe and useful to show the learner. */\nexport class DocumentError extends Error {\n constructor(\n readonly code: DocumentErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport interface ExtractedPage {\n /** 1-based page or slide number. */\n page: number;\n text: string;\n}\n\nexport interface ExtractedDocument {\n kind: \"pdf\" | \"pptx\";\n pageCount: number;\n /** Only the pages that have text. */\n pages: ExtractedPage[];\n}\n\nconst MAX_PAGES = 5000;\nconst MAX_TEXT_CHARS = 10_000_000;\n/** Below this across the whole file there is nothing useful to read: it's images, or at most a stray page number. */\nconst MIN_TEXT_CHARS = 20;\n\nconst MAX_ZIP_ENTRIES = 20_000;\n/** What all entries claim to unpack to, including media that is never unpacked. */\nconst MAX_ZIP_DECLARED_BYTES = 1024 * 1024 * 1024;\n/** What may actually be unpacked: only XML parts are read. */\nconst MAX_XML_PART_BYTES = 32 * 1024 * 1024;\nconst MAX_XML_TOTAL_BYTES = 256 * 1024 * 1024;\n\nconst WRONG_TYPE = \"Only PDF and PowerPoint (.pptx) files can be attached.\";\nconst CORRUPT = \"This file looks damaged and can't be read.\";\nconst ENCRYPTED = \"This file is password-protected. Remove the password and upload it again.\";\nconst TOO_MUCH_TEXT = \"This file has too much text to attach. Try uploading the part you need.\";\n\n/**\n * Keeps text that can be read and searched. Invisible formatting characters go too, since they can\n * hide text from the learner while the model still reads it. Ligatures and maths letters (\uD835\uDC65) become\n * plain ones so a search finds them, while the rest of Unicode, such as \u00B2, is left alone.\n */\nexport function cleanText(text: string): string {\n return text\n .replace(/[^\\P{C}\\n\\t]/gu, \"\")\n .replace(/[\uFB00-\uFB06\\u{1D400}-\\u{1D7FF}]/gu, (c: string) => c.normalize(\"NFKC\"))\n .replace(/[ \\t]+/g, \" \")\n .replace(/ ?\\n ?/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nfunction finish(kind: ExtractedDocument[\"kind\"], pageCount: number, raw: ExtractedPage[]): ExtractedDocument {\n const pages = raw.map(({ page, text }) => ({ page, text: cleanText(text) })).filter((page) => page.text);\n if (pages.reduce((sum, page) => sum + page.text.replace(/\\s/g, \"\").length, 0) < MIN_TEXT_CHARS) {\n throw new DocumentError(\n \"no_text\",\n kind === \"pdf\"\n ? \"This PDF has no readable text; it's probably scanned. Mivra can't read images yet, so try a PDF with selectable text.\"\n : \"These slides have no readable text; they're probably images. Mivra can't read images yet.\",\n );\n }\n return { kind, pageCount, pages };\n}\n\nasync function extractPdf(bytes: Uint8Array): Promise<ExtractedDocument> {\n const { getDocument } = await getResolvedPDFJS();\n // This pdf.js build has no eval path for fonts (the CVE-2024-4367 route); text extraction never renders. It only warns on recoverable damage.\n // pdf.js refuses a Buffer, and takes ownership of what it's given.\n const task = getDocument({ data: new Uint8Array(bytes), useSystemFonts: false, disableFontFace: true, verbosity: 0 });\n try {\n const pdf = await task.promise.catch((error: unknown) => {\n throw (error as Error)?.name === \"PasswordException\" ? new DocumentError(\"encrypted\", ENCRYPTED) : new DocumentError(\"corrupt\", CORRUPT);\n });\n if (pdf.numPages > MAX_PAGES) throw new DocumentError(\"too_complex\", `This PDF has more than ${MAX_PAGES} pages.`);\n const pages: ExtractedPage[] = [];\n let chars = 0;\n for (let page = 1; page <= pdf.numPages; page++) {\n // One bad page shouldn't lose the rest; it counts as a page without text.\n const text = await pdf\n .getPage(page)\n .then(async (handle) => {\n const content = await handle.getTextContent();\n handle.cleanup();\n // Reading order is the file's own, which is usually right for columns but isn't guaranteed.\n return content.items.map((item) => (\"str\" in item ? item.str + (item.hasEOL ? \"\\n\" : \"\") : \"\")).join(\"\");\n })\n .catch(() => \"\");\n chars += text.length;\n if (chars > MAX_TEXT_CHARS) throw new DocumentError(\"too_complex\", TOO_MUCH_TEXT);\n pages.push({ page, text });\n }\n return finish(\"pdf\", pdf.numPages, pages);\n } finally {\n await task.destroy().catch(() => {});\n }\n}\n\n/** The zip's entries by name, with a reader for each that enforces the unpacked-size limits. */\nfunction openZip(bytes: Uint8Array): Promise<{ names: Set<string>; read: (name: string) => Promise<Buffer>; close: () => void }> {\n const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return new Promise((resolve, reject) => {\n // yauzl rejects absolute paths, \"..\" and backslashes in names, and checks entries against their declared sizes.\n yauzl.fromBuffer(buffer, { lazyEntries: true, strictFileNames: true, validateEntrySizes: true }, (openError, zip) => {\n if (openError) return reject(new DocumentError(\"corrupt\", CORRUPT));\n if (zip.entryCount > MAX_ZIP_ENTRIES) return reject(new DocumentError(\"too_complex\", \"This file contains too many parts to read safely.\"));\n const entries = new Map<string, yauzl.Entry>();\n let declared = 0;\n let unpacked = 0;\n zip.on(\"error\", () => reject(new DocumentError(\"corrupt\", CORRUPT)));\n zip.on(\"entry\", (entry: yauzl.Entry) => {\n if (entry.isEncrypted()) return reject(new DocumentError(\"encrypted\", ENCRYPTED));\n declared += entry.uncompressedSize;\n if (declared > MAX_ZIP_DECLARED_BYTES) return reject(new DocumentError(\"too_complex\", \"This file unpacks to too much data to read safely.\"));\n // Two entries with one name could show different content to different readers.\n if (entries.has(entry.fileName)) return reject(new DocumentError(\"corrupt\", CORRUPT));\n entries.set(entry.fileName, entry);\n zip.readEntry();\n });\n const read = (name: string) =>\n new Promise<Buffer>((done, fail) => {\n const entry = entries.get(name);\n if (!entry) return fail(new DocumentError(\"corrupt\", CORRUPT));\n const tooMuch = new DocumentError(\"too_complex\", \"This file unpacks to too much data to read safely.\");\n if (entry.uncompressedSize > MAX_XML_PART_BYTES) return fail(tooMuch);\n zip.openReadStream(entry, (streamError, stream) => {\n if (streamError) return fail(new DocumentError(\"corrupt\", CORRUPT));\n const chunks: Buffer[] = [];\n stream.on(\"data\", (chunk: Buffer) => {\n unpacked += chunk.length;\n if (unpacked > MAX_XML_TOTAL_BYTES) stream.destroy(tooMuch);\n else chunks.push(chunk);\n });\n stream.on(\"error\", (error) => fail(error instanceof DocumentError ? error : new DocumentError(\"corrupt\", CORRUPT)));\n stream.on(\"end\", () => done(Buffer.concat(chunks)));\n });\n });\n zip.on(\"end\", () => resolve({ names: new Set(entries.keys()), read, close: () => zip.close() }));\n zip.readEntry();\n });\n });\n}\n\n/** Office XML is UTF-8 or UTF-16. Any other declared encoding reads as damaged text, not as a risk. */\nfunction decodeXml(bytes: Buffer): string {\n const [a, b] = bytes;\n const encoding = (a === 0xff && b === 0xfe) || (a === 0x3c && b === 0) ? \"utf-16le\" : (a === 0xfe && b === 0xff) || (a === 0 && b === 0x3c) ? \"utf-16be\" : \"utf-8\";\n const xml = new TextDecoder(encoding).decode(bytes);\n // Office never writes a DTD, so one means a crafted file. Nothing here expands entities anyway: see xmlTokens.\n if (/<!(DOCTYPE|ENTITY)/i.test(xml)) throw new DocumentError(\"corrupt\", \"This file contains unsafe XML and can't be read.\");\n return xml;\n}\n\nconst NAMED_ENTITIES: Record<string, string> = { amp: \"&\", lt: \"<\", gt: \">\", quot: '\"', apos: \"'\" };\n\n/** The five predefined entities and character references. Any other entity stays as literal text. */\nfunction decodeEntities(text: string): string {\n return text.replace(/&(?:#(\\d{1,7})|#x([\\da-f]{1,6})|(amp|lt|gt|quot|apos));/gi, (whole, dec?: string, hex?: string, name?: string) => {\n if (name) return NAMED_ENTITIES[name.toLowerCase()] ?? whole;\n const code = dec ? Number(dec) : parseInt(hex!, 16);\n return code <= 0x10ffff ? String.fromCodePoint(code) : whole;\n });\n}\n\n/** Splits XML into tags and text without interpreting it, which is all these few element types need. */\nfunction* xmlTokens(xml: string) {\n for (const [token] of xml.matchAll(/<!--[\\s\\S]*?-->|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|<[^>]*>|[^<]+/g)) {\n if (token.startsWith(\"<!--\") || token.startsWith(\"<?\")) continue;\n if (token.startsWith(\"<![CDATA[\")) yield { text: token.slice(9, -3) };\n else if (token.startsWith(\"<\")) {\n const name = /^<\\/?(?:[\\w.-]+:)?([\\w.-]+)/.exec(token)?.[1] ?? \"\";\n yield { tag: token, name, closing: token.startsWith(\"</\"), selfClosing: token.endsWith(\"/>\") };\n } else yield { text: decodeEntities(token) };\n }\n}\n\n/** Slide text: `a:t` runs and `m:t` equation runs, without `mc:Fallback`, which repeats content for old readers. */\nfunction slideText(xml: string): string {\n let out = \"\";\n let inText = 0;\n let inFallback = 0;\n for (const token of xmlTokens(xml)) {\n if (\"text\" in token) {\n if (inText > 0 && inFallback === 0) out += token.text;\n continue;\n }\n const delta = token.selfClosing ? 0 : token.closing ? -1 : 1;\n if (token.name === \"Fallback\") inFallback = Math.max(0, inFallback + delta);\n else if (token.name === \"t\") inText = Math.max(0, inText + delta);\n else if (inFallback === 0 && (token.name === \"br\" || (token.name === \"p\" && token.closing))) out += \"\\n\";\n }\n return out;\n}\n\nconst attribute = (tag: string, name: RegExp) => new RegExp(`\\\\s${name.source}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`).exec(tag)?.[1];\n\n/** The presentation's slide parts in the order it shows them, which needn't match their file names. */\nfunction slideOrder(presentationXml: string, relsXml: string): (string | undefined)[] {\n const targets = new Map<string, string>();\n for (const token of xmlTokens(relsXml)) {\n if (\"tag\" in token && token.name === \"Relationship\" && !token.closing) {\n const id = attribute(token.tag, /Id/);\n const target = attribute(token.tag, /Target/);\n if (id && target) targets.set(id, target);\n }\n }\n const slides: (string | undefined)[] = [];\n for (const token of xmlTokens(presentationXml)) {\n if (\"tag\" in token && token.name === \"sldId\" && !token.closing) {\n const target = targets.get(attribute(token.tag, /[\\w.-]+:id/) ?? \"\");\n // Relationship targets come from the file, so only a part directly under ppt/slides is ever opened.\n const part = target && (target.startsWith(\"/\") ? posix.normalize(target).slice(1) : posix.join(\"ppt\", target));\n slides.push(part && /^ppt\\/slides\\/[^/]+\\.xml$/.test(part) ? part : undefined);\n }\n }\n return slides;\n}\n\nasync function extractPptx(bytes: Uint8Array): Promise<ExtractedDocument> {\n const zip = await openZip(bytes);\n try {\n if (!zip.names.has(\"[Content_Types].xml\")) throw new DocumentError(\"wrong_type\", WRONG_TYPE);\n const types = decodeXml(await zip.read(\"[Content_Types].xml\"));\n if (!/officedocument\\.presentationml\\.(presentation|slideshow|template)\\.main\\+xml/i.test(types)) throw new DocumentError(\"wrong_type\", WRONG_TYPE);\n if (!zip.names.has(\"ppt/presentation.xml\") || !zip.names.has(\"ppt/_rels/presentation.xml.rels\")) throw new DocumentError(\"corrupt\", CORRUPT);\n\n const slides = slideOrder(decodeXml(await zip.read(\"ppt/presentation.xml\")), decodeXml(await zip.read(\"ppt/_rels/presentation.xml.rels\")));\n if (slides.length > MAX_PAGES) throw new DocumentError(\"too_complex\", `This file has more than ${MAX_PAGES} slides.`);\n const pages: ExtractedPage[] = [];\n let chars = 0;\n for (const [index, part] of slides.entries()) {\n if (!part || !zip.names.has(part)) continue;\n const text = slideText(decodeXml(await zip.read(part)));\n chars += text.length;\n if (chars > MAX_TEXT_CHARS) throw new DocumentError(\"too_complex\", TOO_MUCH_TEXT);\n pages.push({ page: index + 1, text });\n }\n return finish(\"pptx\", slides.length, pages);\n } finally {\n zip.close();\n }\n}\n\nconst startsWith = (bytes: Uint8Array, magic: number[]) => magic.every((byte, i) => bytes[i] === byte);\n\n/** Dispatches on what the file contains, whatever it is called. */\nexport async function extractDocument(bytes: Uint8Array): Promise<ExtractedDocument> {\n const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n // The PDF spec lets a header sit a little way into the file.\n if (buffer.subarray(0, 1024).includes(\"%PDF-\")) return extractPdf(bytes);\n if (startsWith(bytes, [0x50, 0x4b, 0x03, 0x04])) return extractPptx(bytes);\n // Office stores a password-protected .pptx in the same container as an old .ppt.\n if (startsWith(bytes, [0xd0, 0xcf, 0x11, 0xe0]) && buffer.includes(Buffer.from(\"EncryptedPackage\", \"utf16le\"))) throw new DocumentError(\"encrypted\", ENCRYPTED);\n throw new DocumentError(\"wrong_type\", WRONG_TYPE);\n}\n", "import type { SkipReason } from \"@mivra/protocol\";\n\n// Kept apart from the importer so the zip subprocess (vault-zip.ts) can check paths without loading the database code.\n\nexport type SkippedFile = { path: string; reason: SkipReason };\n\n/**\n * A safe vault path, or why the file is skipped. Paths come from the client, so absolute paths, `..`, empty\n * segments and NUL are refused outright. Hidden folders such as `.obsidian` and `.trash` hold config and\n * deleted notes, not notes.\n */\nexport function cleanVaultPath(raw: string): { path: string } | { reason: SkipReason } {\n let path = raw.replace(/\\\\/g, \"/\").normalize(\"NFC\");\n if (path.includes(\"\\0\") || path.startsWith(\"/\") || /^[A-Za-z]:/.test(path)) return { reason: \"bad_path\" };\n path = path.replace(/^(\\.\\/)+/, \"\");\n const segments = path.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) return { reason: \"bad_path\" };\n if (segments.some((s) => s.startsWith(\".\"))) return { reason: \"hidden\" };\n if (!/\\.md$/i.test(path)) return { reason: \"not_markdown\" };\n return { path };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,aAAa;AACtB,S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,KAAK;AAChB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// ../server/src/models/key-check.ts
|
|
2
|
+
var TIMEOUT_MS = 1e4;
|
|
3
|
+
function probe(provider, key, baseUrl) {
|
|
4
|
+
const base = (fallback) => (baseUrl ?? fallback).replace(/\/$/, "");
|
|
5
|
+
switch (provider) {
|
|
6
|
+
case "openrouter":
|
|
7
|
+
return { url: "https://openrouter.ai/api/v1/key", headers: { authorization: `Bearer ${key}` } };
|
|
8
|
+
case "anthropic":
|
|
9
|
+
return { url: `${base("https://api.anthropic.com/v1")}/models?limit=1`, headers: { "x-api-key": key, "anthropic-version": "2023-06-01" } };
|
|
10
|
+
case "openai":
|
|
11
|
+
return { url: `${base("https://api.openai.com/v1")}/models`, headers: { authorization: `Bearer ${key}` } };
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
async function checkProviderKey(provider, key, { fetch: fetchImpl = fetch, baseUrl } = {}) {
|
|
15
|
+
const { url, headers } = probe(provider, key, baseUrl);
|
|
16
|
+
let response;
|
|
17
|
+
try {
|
|
18
|
+
response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
19
|
+
} catch {
|
|
20
|
+
return { ok: false, reason: "unreachable", message: "Couldn't reach the provider. Check your connection and try again." };
|
|
21
|
+
}
|
|
22
|
+
await response.body?.cancel().catch(() => {
|
|
23
|
+
});
|
|
24
|
+
if (response.ok) return { ok: true };
|
|
25
|
+
if (response.status === 401 || response.status === 403) return { ok: false, reason: "rejected", message: "The provider rejected this key." };
|
|
26
|
+
return { ok: false, reason: "unreachable", message: `The provider answered ${response.status}. Try again later.` };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
checkProviderKey
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=chunk-TBAR47I6.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../server/src/models/key-check.ts"],
|
|
4
|
+
"sourcesContent": ["import type { ProviderId } from \"../credentials.js\";\n\nexport type KeyCheck = { ok: true } | { ok: false; reason: \"rejected\" | \"unreachable\"; message: string };\n\nconst TIMEOUT_MS = 10_000;\n\n/** One authenticated request that costs nothing: each provider's key or model-list endpoint. */\nfunction probe(provider: ProviderId, key: string, baseUrl: string | undefined): { url: string; headers: Record<string, string> } {\n const base = (fallback: string) => (baseUrl ?? fallback).replace(/\\/$/, \"\");\n switch (provider) {\n case \"openrouter\":\n return { url: \"https://openrouter.ai/api/v1/key\", headers: { authorization: `Bearer ${key}` } };\n case \"anthropic\":\n return { url: `${base(\"https://api.anthropic.com/v1\")}/models?limit=1`, headers: { \"x-api-key\": key, \"anthropic-version\": \"2023-06-01\" } };\n case \"openai\":\n return { url: `${base(\"https://api.openai.com/v1\")}/models`, headers: { authorization: `Bearer ${key}` } };\n }\n}\n\n/** Checks that the provider accepts a key, without spending tokens (ADR-013). */\nexport async function checkProviderKey(\n provider: ProviderId,\n key: string,\n { fetch: fetchImpl = fetch, baseUrl }: { fetch?: typeof fetch; baseUrl?: string } = {},\n): Promise<KeyCheck> {\n const { url, headers } = probe(provider, key, baseUrl);\n let response: Response;\n try {\n response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });\n } catch {\n return { ok: false, reason: \"unreachable\", message: \"Couldn't reach the provider. Check your connection and try again.\" };\n }\n // The body isn't needed; release the connection.\n await response.body?.cancel().catch(() => {});\n if (response.ok) return { ok: true };\n if (response.status === 401 || response.status === 403) return { ok: false, reason: \"rejected\", message: \"The provider rejected this key.\" };\n return { ok: false, reason: \"unreachable\", message: `The provider answered ${response.status}. Try again later.` };\n}\n"],
|
|
5
|
+
"mappings": ";AAIA,IAAM,aAAa;AAGnB,SAAS,MAAM,UAAsB,KAAa,SAA+E;AAC/H,QAAM,OAAO,CAAC,cAAsB,WAAW,UAAU,QAAQ,OAAO,E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