amicooked 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,287 @@
1
+ import { z } from "zod";
2
+ import { getToken } from "../auth.js";
3
+ import { client, D2LApiError } from "../client.js";
4
+ import { currentCourses, listCourses, matchCourses } from "../courseResolver.js";
5
+ import { getSchool } from "../config.js";
6
+ import { classifyDateEvent, DateType } from "../utils/dateEvent.js";
7
+ import { isSubmitted, stripHtml } from "../utils/marshal.js";
8
+ const DAY = 24 * 60 * 60 * 1000;
9
+ // ---- pure aggregation ----
10
+ const round1 = (n) => Math.round(n * 10) / 10;
11
+ /** Grade items that count: numeric, pass/fail and select-box items with a score. */
12
+ const SCORED_TYPES = new Set([1, 2, 3]);
13
+ /**
14
+ * Weighted average over graded items, falling back to points when the course has no weights.
15
+ * Also says how much of the final grade is graded so far, and which items matter most, so nobody
16
+ * has to work the weights out backwards from the result.
17
+ */
18
+ export function estimateGrade(items) {
19
+ const graded = items.filter((g) => SCORED_TYPES.has(g.GradeObjectType) && g.PointsNumerator !== null);
20
+ const weighted = graded.filter((g) => g.WeightedNumerator !== null && g.WeightedDenominator);
21
+ const byWeight = weighted.length > 0;
22
+ const pool = byWeight ? weighted : graded.filter((g) => g.PointsDenominator);
23
+ const part = (g) => byWeight ? [g.WeightedNumerator, g.WeightedDenominator] : [g.PointsNumerator, g.PointsDenominator];
24
+ const [num, den] = pool.reduce(([n, d], g) => [n + part(g)[0], d + part(g)[1]], [0, 0]);
25
+ if (!den)
26
+ return { percent: null, gradedItems: graded.length };
27
+ const percent = round1((num / den) * 100);
28
+ // The items pulling the estimate down hardest come first, then the heaviest
29
+ const keyItems = pool
30
+ .map((g) => {
31
+ const [n, d] = part(g);
32
+ return { name: g.GradeObjectName.trim(), percent: round1((n / d) * 100), size: d };
33
+ })
34
+ .sort((a, b) => (percent - b.percent) * b.size - (percent - a.percent) * a.size || b.size - a.size)
35
+ .slice(0, 3)
36
+ .map(({ name, percent: p, size }) => (byWeight ? { name, percent: p, weight: round1(size) } : { name, percent: p }));
37
+ const estimate = { percent, gradedItems: graded.length, basis: byWeight ? "gradebook_weights" : "points", keyItems };
38
+ // Weights are percent of the final grade; a total over 100 means the gradebook isn't out of 100
39
+ if (byWeight && den <= 100.5) {
40
+ estimate.weightGraded = round1(den);
41
+ estimate.weightRemaining = round1(Math.max(0, 100 - den));
42
+ }
43
+ return estimate;
44
+ }
45
+ function finalPercent(g) {
46
+ if (g.PointsNumerator !== null && g.PointsDenominator)
47
+ return round1((g.PointsNumerator / g.PointsDenominator) * 100);
48
+ const shown = g.DisplayedGrade?.match(/([\d.]+)\s*%/);
49
+ return shown ? Number(shown[1]) : null;
50
+ }
51
+ export function buildCourseReport(course, data, w) {
52
+ const errors = [...data.errors];
53
+ const horizon = w.now + w.daysAhead * DAY;
54
+ const overdueFrom = w.now - w.overdueDaysBack * DAY;
55
+ // Grade: the released final calculated grade wins, otherwise estimate from items
56
+ let grade = { percent: null, display: null, source: "none", gradedItems: 0 };
57
+ const estimate = data.gradeItems ? estimateGrade(data.gradeItems) : { percent: null, gradedItems: 0 };
58
+ const final = data.finalGrade ? finalPercent(data.finalGrade) : null;
59
+ if (final !== null) {
60
+ grade = { percent: final, display: data.finalGrade.DisplayedGrade?.trim() || null, source: "final_calculated", gradedItems: estimate.gradedItems };
61
+ }
62
+ else if (estimate.percent !== null) {
63
+ grade = { ...estimate, display: `${estimate.percent}%`, source: "estimated_from_items" };
64
+ }
65
+ // Assignments due soon, and overdue ones without a submission
66
+ const dueSoon = [];
67
+ const overdue = [];
68
+ const dropboxIds = new Set();
69
+ for (const { folder, submitted } of data.folders ?? []) {
70
+ if (folder.IsHidden)
71
+ continue;
72
+ const dueIso = folder.DueDate ?? folder.Availability?.EndDate ?? null;
73
+ if (!dueIso)
74
+ continue;
75
+ const due = Date.parse(dueIso);
76
+ dropboxIds.add(folder.Id);
77
+ if (due > w.now && due <= horizon) {
78
+ dueSoon.push({
79
+ title: folder.Name,
80
+ type: "assignment",
81
+ due: dueIso,
82
+ dueInHours: Math.round((due - w.now) / 3600000),
83
+ submitted,
84
+ ...(folder.Assessment?.ScoreDenominator ? { points: folder.Assessment.ScoreDenominator } : {}),
85
+ assignmentId: folder.Id,
86
+ });
87
+ }
88
+ else if (due <= w.now && due >= overdueFrom && submitted === false) {
89
+ const closes = folder.Availability?.EndDate ? Date.parse(folder.Availability.EndDate) : null;
90
+ overdue.push({
91
+ title: folder.Name,
92
+ due: dueIso,
93
+ daysLate: Math.floor((w.now - due) / DAY),
94
+ stillOpenUntil: closes && closes > w.now ? folder.Availability.EndDate : null,
95
+ assignmentId: folder.Id,
96
+ });
97
+ }
98
+ }
99
+ // Calendar adds quizzes and exams; dropbox events are already covered above
100
+ for (const e of data.events ?? []) {
101
+ const entity = e.AssociatedEntity;
102
+ if (entity?.AssociatedEntityType.includes("Dropbox") && dropboxIds.has(entity.AssociatedEntityId))
103
+ continue;
104
+ const due = Date.parse(e.EndDateTime);
105
+ if (!(due > w.now && due <= horizon))
106
+ continue;
107
+ const { dateType } = classifyDateEvent(e.Title, stripHtml(e.Description), entity?.AssociatedEntityType ?? null);
108
+ const isQuiz = entity?.AssociatedEntityType.includes("Quiz");
109
+ if (!isQuiz && dateType !== DateType.DUE && dateType !== DateType.EXAM)
110
+ continue;
111
+ dueSoon.push({
112
+ title: e.Title,
113
+ type: isQuiz ? "quiz" : dateType === DateType.EXAM ? "exam" : "event",
114
+ due: e.EndDateTime,
115
+ dueInHours: Math.round((due - w.now) / 3600000),
116
+ submitted: null,
117
+ });
118
+ }
119
+ dueSoon.sort((a, b) => a.due.localeCompare(b.due));
120
+ const since = w.now - w.announcementsDays * DAY;
121
+ const recentNews = (data.news ?? [])
122
+ .filter((n) => !n.IsHidden && n.StartDate && Date.parse(n.StartDate) >= since)
123
+ .sort((a, b) => b.StartDate.localeCompare(a.StartDate));
124
+ const signals = [];
125
+ if (grade.percent !== null && grade.percent < 60)
126
+ signals.push("grade_below_60");
127
+ else if (grade.percent !== null && grade.percent < 70)
128
+ signals.push("grade_below_70");
129
+ if (overdue.length)
130
+ signals.push("overdue_work");
131
+ if (overdue.some((o) => o.stillOpenUntil))
132
+ signals.push("late_window_open");
133
+ if (dueSoon.length >= 3)
134
+ signals.push("heavy_week");
135
+ if (grade.source === "none")
136
+ signals.push("no_grades_released");
137
+ if (errors.length)
138
+ signals.push("partial_data");
139
+ return {
140
+ id: course.id,
141
+ code: course.code,
142
+ name: course.name,
143
+ grade,
144
+ dueSoon,
145
+ overdue,
146
+ announcements: { count: recentNews.length, latest: recentNews.slice(0, 3).map((n) => ({ title: n.Title, date: n.StartDate })) },
147
+ signals,
148
+ errors,
149
+ };
150
+ }
151
+ export const HEAT_LABELS = ["raw", "warming up", "toasty", "cooked", "well done"];
152
+ /**
153
+ * 0-10: +2 per unsubmitted overdue item, +1 per unsubmitted item due within 72h,
154
+ * +3/+2/+1 for a grade under 50/60/70.
155
+ */
156
+ export function heatScore(reports) {
157
+ let heat = 0;
158
+ const reasons = [];
159
+ for (const r of reports) {
160
+ if (r.overdue.length) {
161
+ heat += 2 * r.overdue.length;
162
+ reasons.push(`${r.overdue.length} overdue in ${r.code}`);
163
+ }
164
+ const urgent = r.dueSoon.filter((d) => d.dueInHours <= 72 && d.submitted !== true);
165
+ if (urgent.length) {
166
+ heat += urgent.length;
167
+ reasons.push(`${urgent.length} due within 3 days in ${r.code}`);
168
+ }
169
+ const p = r.grade.percent;
170
+ if (p !== null && p < 70) {
171
+ heat += p < 50 ? 3 : p < 60 ? 2 : 1;
172
+ reasons.push(`${p}% in ${r.code}`);
173
+ }
174
+ }
175
+ heat = Math.min(heat, 10);
176
+ return { heat, heatLabel: heatLabel(heat), reasons };
177
+ }
178
+ /** Bands match the doneness meter on the website: 0-1, 2-3, 4-5, 6-7, 8-10. */
179
+ export function heatLabel(heat) {
180
+ return HEAT_LABELS[Math.min(Math.floor(heat / 2), HEAT_LABELS.length - 1)];
181
+ }
182
+ // ---- fetching ----
183
+ const errorMessage = (e) => (e instanceof Error ? e.message : String(e));
184
+ async function part(name, errors, fn) {
185
+ try {
186
+ return await fn();
187
+ }
188
+ catch (error) {
189
+ errors.push({ part: name, message: errorMessage(error).slice(0, 160) });
190
+ return null;
191
+ }
192
+ }
193
+ async function fetchCourseData(course, w) {
194
+ const errors = [];
195
+ const start = new Date(w.now - w.overdueDaysBack * DAY).toISOString();
196
+ const end = new Date(w.now + w.daysAhead * DAY).toISOString();
197
+ const [finalGrade, gradeItems, folders, events, news] = await Promise.all([
198
+ part("final_grade", errors, async () => {
199
+ try {
200
+ return (await client.getMyFinalGrade(course.id));
201
+ }
202
+ catch (error) {
203
+ // Not released yet is normal, not an error
204
+ if (error instanceof D2LApiError && (error.status === 403 || error.status === 404))
205
+ return null;
206
+ throw error;
207
+ }
208
+ }),
209
+ part("grades", errors, async () => (await client.getMyGradeValues(course.id))),
210
+ part("assignments", errors, async () => {
211
+ const all = (await client.getDropboxFolders(course.id));
212
+ // Only check submissions for folders in the window; that's where "submitted?" matters
213
+ return Promise.all(all.map(async (folder) => {
214
+ const dueIso = folder.DueDate ?? folder.Availability?.EndDate;
215
+ const due = dueIso ? Date.parse(dueIso) : NaN;
216
+ const inWindow = due >= w.now - w.overdueDaysBack * DAY && due <= w.now + w.daysAhead * DAY;
217
+ if (folder.IsHidden || !inWindow)
218
+ return { folder, submitted: null };
219
+ try {
220
+ const subs = (await client.getDropboxSubmissions(course.id, folder.Id));
221
+ return { folder, submitted: subs.some(isSubmitted) };
222
+ }
223
+ catch {
224
+ return { folder, submitted: null };
225
+ }
226
+ }));
227
+ }),
228
+ part("calendar", errors, async () => (await client.getMyCalendarEvents(course.id, start, end)).Objects),
229
+ part("announcements", errors, async () => (await client.getNews(course.id))),
230
+ ]);
231
+ return { finalGrade, gradeItems, folders, events, news, errors };
232
+ }
233
+ export async function amICooked(args) {
234
+ // Log in once up front so a fan-out over every course doesn't race to open login windows
235
+ await getToken();
236
+ const w = {
237
+ now: Date.now(),
238
+ daysAhead: args.daysAhead ?? 7,
239
+ overdueDaysBack: args.overdueDaysBack ?? 14,
240
+ announcementsDays: args.announcementsDays ?? 7,
241
+ };
242
+ const all = await listCourses();
243
+ const selected = args.courses?.length
244
+ ? [...new Map(args.courses.flatMap((q) => matchCourses(all, q)).map((c) => [c.id, c])).values()]
245
+ : currentCourses(all);
246
+ // Students accumulate years of old courses; a count and a few names are enough to explain the gap
247
+ const skippedCodes = all.filter((c) => c.isActive && !selected.some((s) => s.id === c.id)).map((c) => c.code);
248
+ const skipped = { count: skippedCodes.length, examples: skippedCodes.slice(-5), howToInclude: 'Pass courses: ["CODE"] to include one.' };
249
+ const courses = await Promise.all(selected.map(async (c) => buildCourseReport(c, await fetchCourseData(c, w), w)));
250
+ const { heat, heatLabel, reasons } = heatScore(courses);
251
+ const graded = courses.filter((c) => c.grade.percent !== null);
252
+ const lowest = graded.sort((a, b) => a.grade.percent - b.grade.percent)[0];
253
+ return {
254
+ generatedAt: new Date(w.now).toISOString(),
255
+ school: getSchool().name,
256
+ window: { daysAhead: w.daysAhead, overdueDaysBack: w.overdueDaysBack },
257
+ summary: {
258
+ heat,
259
+ heatLabel,
260
+ reasons,
261
+ courses: courses.length,
262
+ dueSoon: courses.reduce((n, c) => n + c.dueSoon.length, 0),
263
+ overdue: courses.reduce((n, c) => n + c.overdue.length, 0),
264
+ newAnnouncements: courses.reduce((n, c) => n + c.announcements.count, 0),
265
+ lowestGrade: lowest ? { course: lowest.code, percent: lowest.grade.percent, source: lowest.grade.source } : null,
266
+ },
267
+ courses: courses.sort((a, b) => a.code.localeCompare(b.code)),
268
+ skippedCourses: skipped,
269
+ notes: [
270
+ "Times are UTC; convert to the student's local time.",
271
+ "estimated_from_items grades ignore dropped or bonus items, so treat them as rough.",
272
+ "weightRemaining is the percent of the final grade still to come. basis \"points\" means the gradebook has no weights, so the real weighting may differ.",
273
+ "Quiz completion isn't known (submitted: null).",
274
+ ],
275
+ };
276
+ }
277
+ export const amICookedTool = {
278
+ name: "am_i_cooked",
279
+ description: 'One-call overview across all current courses: grade so far, what is due soon, overdue unsubmitted work, and new announcements, plus a heat score (0-10: raw, warming up, toasty, cooked, well done). Start here for "am I cooked?", "what should I work on?", "how am I doing?" or "what\'s due this week?".',
280
+ schema: {
281
+ daysAhead: z.coerce.number().min(1).max(60).optional().describe("How far ahead to look for due dates (default 7)"),
282
+ overdueDaysBack: z.coerce.number().min(0).max(60).optional().describe("How far back to look for missed work (default 14)"),
283
+ announcementsDays: z.coerce.number().min(1).max(60).optional().describe("Count announcements from the last N days (default 7)"),
284
+ courses: z.array(z.string()).optional().describe('Limit to these course codes or names, e.g. ["3BB4"]'),
285
+ },
286
+ handler: async (args) => JSON.stringify(await amICooked(args)),
287
+ };
@@ -0,0 +1,28 @@
1
+ import { client } from "../client.js";
2
+ import { courseParams, listCourses, resolveCourse } from "../courseResolver.js";
3
+ import { marshalAnnouncements, marshalGrades } from "../utils/marshal.js";
4
+ import { json } from "./types.js";
5
+ export const getMyCourses = {
6
+ name: "get_my_courses",
7
+ description: 'List the courses you can open, with code, name, ID and whether they are active. Other tools take a course code like "3BB4" directly, so you only need this to see what exists or to settle an ambiguous code.',
8
+ schema: {},
9
+ handler: async () => json(await listCourses()),
10
+ };
11
+ export const getMyGrades = {
12
+ name: "get_my_grades",
13
+ description: 'Your grade items for one course: item name, points earned and possible, percentage, weight toward the final grade (when the gradebook has weights) and instructor feedback. Use for "what did I get on the midterm?" or "what\'s my grade in 3BB4?". For an overview across all courses, use am_i_cooked.',
14
+ schema: { ...courseParams },
15
+ handler: async (args) => {
16
+ const grades = (await client.getMyGradeValues(await resolveCourse(args)));
17
+ return json(marshalGrades(grades));
18
+ },
19
+ };
20
+ export const getAnnouncements = {
21
+ name: "get_announcements",
22
+ description: "Announcements (news) your instructors posted in one course: title, body, date, attachments. Check these before giving a verdict, since deadlines and exam details often change here.",
23
+ schema: { ...courseParams },
24
+ handler: async (args) => {
25
+ const news = (await client.getNews(await resolveCourse(args)));
26
+ return json(marshalAnnouncements(news));
27
+ },
28
+ };
@@ -0,0 +1,59 @@
1
+ import { z } from "zod";
2
+ import { client } from "../client.js";
3
+ import { courseParams, currentCourses, listCourses, resolveCourse } from "../courseResolver.js";
4
+ import { isSubmitted, marshalAssignment, marshalCalendarEvents, marshalSubmissions, } from "../utils/marshal.js";
5
+ import { json } from "./types.js";
6
+ const DAY = 24 * 60 * 60 * 1000;
7
+ export const getUpcomingDueDates = {
8
+ name: "get_upcoming_due_dates",
9
+ description: "Calendar due dates and events (assignments, quizzes, exams) sorted by date. Leave out the course to get every current course at once. Defaults to 7 days back and 30 days ahead.",
10
+ schema: {
11
+ ...courseParams,
12
+ daysBack: z.coerce.number().min(0).max(120).optional().describe("Days in the past to include (default 7)"),
13
+ daysAhead: z.coerce.number().min(0).max(180).optional().describe("Days ahead to include (default 30)"),
14
+ },
15
+ handler: async (args) => {
16
+ const now = Date.now();
17
+ const start = new Date(now - (args.daysBack ?? 7) * DAY).toISOString();
18
+ const end = new Date(now + (args.daysAhead ?? 30) * DAY).toISOString();
19
+ const ids = args.course || args.orgUnitId
20
+ ? [await resolveCourse(args)]
21
+ : currentCourses(await listCourses()).map((c) => c.id);
22
+ const results = await Promise.allSettled(ids.map(async (id) => (await client.getMyCalendarEvents(id, start, end))));
23
+ const events = results.flatMap((r) => (r.status === "fulfilled" ? r.value.Objects : []));
24
+ const failed = results.filter((r) => r.status === "rejected").length;
25
+ const sorted = marshalCalendarEvents({ Objects: events }).sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""));
26
+ return json(failed ? { events: sorted, note: `${failed} course(s) couldn't be loaded` } : sorted);
27
+ },
28
+ };
29
+ export const getAssignments = {
30
+ name: "get_assignments",
31
+ description: 'Assignments (dropbox folders) in one course with due dates and whether you submitted each one. Pass assignmentId for full instructions, attachments, your submitted files, grade and feedback. Use for "did I submit lab 4?" or "what does assignment 2 ask for?".',
32
+ schema: {
33
+ ...courseParams,
34
+ assignmentId: z.coerce.number().optional().describe("Assignment ID from the list, for full details and your submission"),
35
+ },
36
+ handler: async (args) => {
37
+ const orgUnitId = await resolveCourse(args);
38
+ if (args.assignmentId) {
39
+ const [folder, submissions] = await Promise.all([
40
+ client.getDropboxFolder(orgUnitId, args.assignmentId),
41
+ client.getDropboxSubmissions(orgUnitId, args.assignmentId),
42
+ ]);
43
+ return json({ ...marshalAssignment(folder), submissions: marshalSubmissions(submissions) });
44
+ }
45
+ const folders = (await client.getDropboxFolders(orgUnitId));
46
+ const visible = folders.filter((f) => !f.IsHidden);
47
+ const list = await Promise.all(visible.map(async (folder) => {
48
+ const { instructions: _, ...summary } = marshalAssignment(folder);
49
+ try {
50
+ const subs = (await client.getDropboxSubmissions(orgUnitId, folder.Id));
51
+ return { ...summary, submitted: subs.some(isSubmitted) };
52
+ }
53
+ catch {
54
+ return { ...summary, submitted: null };
55
+ }
56
+ }));
57
+ return json(list);
58
+ },
59
+ };
@@ -0,0 +1,143 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { z } from "zod";
4
+ import { getD2LCookies, hasActiveSession, clearTokenCache } from "../auth.js";
5
+ import { client } from "../client.js";
6
+ import { getConfig, getSchool } from "../config.js";
7
+ import { listCourses } from "../courseResolver.js";
8
+ import { extractContent } from "../extract.js";
9
+ import { getFile, listEntries, readTextCached } from "../library.js";
10
+ import { json } from "./types.js";
11
+ /** Keep tool results a sensible size; read_file's offset pages through the rest. */
12
+ const MAX_CHARS = 60000;
13
+ export function sanitizeName(name) {
14
+ const cleaned = name
15
+ .replace(/[\/\\:*?"<>|\x00-\x1f]/g, "-")
16
+ .replace(/\s+/g, " ")
17
+ .replace(/^[.\s]+|[.\s]+$/g, "")
18
+ .slice(0, 120);
19
+ return cleaned || "untitled";
20
+ }
21
+ function page(text, offset = 0) {
22
+ if (text === null)
23
+ return { content: null, note: "No text could be extracted (image, scanned PDF or unsupported format)." };
24
+ const content = text.slice(offset, offset + MAX_CHARS);
25
+ const rest = text.length - offset - content.length;
26
+ return rest > 0
27
+ ? { content, note: `Showing characters ${offset}-${offset + content.length} of ${text.length}. Call read_file with offset ${offset + content.length} for more.` }
28
+ : { content };
29
+ }
30
+ const TOC_TTL_MS = 10 * 60 * 1000;
31
+ const tocCache = new Map();
32
+ /** Find which module (folder path) and topic title a file URL belongs to in the course's content. */
33
+ async function locateTopic(orgUnitId, fileUrl) {
34
+ let cached = tocCache.get(orgUnitId);
35
+ if (!cached || Date.now() - cached.at > TOC_TTL_MS) {
36
+ const toc = (await client.getContentToc(orgUnitId));
37
+ cached = { at: Date.now(), modules: toc.Modules || [] };
38
+ tocCache.set(orgUnitId, cached);
39
+ }
40
+ const target = decodeURIComponent(new URL(fileUrl).pathname);
41
+ const search = (modules, trail) => {
42
+ for (const mod of modules) {
43
+ const here = [...trail, mod.Title];
44
+ for (const topic of mod.Topics || []) {
45
+ if (topic.Url && decodeURIComponent(topic.Url.split("?")[0]) === target)
46
+ return { modulePath: here, title: topic.Title };
47
+ }
48
+ const found = search(mod.Modules || [], here);
49
+ if (found)
50
+ return found;
51
+ }
52
+ return null;
53
+ };
54
+ return search(cached.modules, []);
55
+ }
56
+ /** GET a D2L file with the session cookies; retries once with a fresh login if the session expired. */
57
+ async function fetchD2L(url, headers) {
58
+ for (let attempt = 0; attempt < 2; attempt++) {
59
+ let target = url;
60
+ let res = null;
61
+ for (let hop = 0; hop < 5; hop++) {
62
+ res = await fetch(target, { headers: { ...headers, Cookie: await getD2LCookies() }, redirect: "manual" });
63
+ const location = res.headers.get("location");
64
+ if (res.status < 300 || res.status >= 400 || res.status === 304 || !location)
65
+ break;
66
+ target = new URL(location, target).toString();
67
+ }
68
+ if (res && new URL(target).pathname.startsWith("/d2l/login")) {
69
+ clearTokenCache();
70
+ continue;
71
+ }
72
+ if (res && (res.ok || res.status === 304))
73
+ return res;
74
+ throw new Error(`D2L returned ${res?.status} for ${url}`);
75
+ }
76
+ throw new Error("Your D2L session expired and logging in again failed.");
77
+ }
78
+ async function downloadFile(url, refresh) {
79
+ const fullUrl = new URL(url, `https://${getSchool().host}`).toString();
80
+ const urlPath = decodeURIComponent(new URL(fullUrl).pathname);
81
+ const urlFilename = urlPath.split("/").filter(Boolean).pop() || "download";
82
+ // /content/enforced/781481-SFWRENG_3O03_deza_1_2269/file.pdf, or an org unit id elsewhere in the path
83
+ const enforced = urlPath.match(/\/content\/enforced\/(\d+)-([^/]+)\//);
84
+ const orgUnitId = enforced ? Number(enforced[1]) : Number(urlPath.match(/\/(\d{5,})(?:\/|$)/)?.[1]) || null;
85
+ // Course and module lookups hit the API, so only resolve the folder on a first download
86
+ const resolveTarget = async () => {
87
+ const course = orgUnitId ? (await listCourses().catch(() => [])).find((c) => c.id === orgUnitId) : undefined;
88
+ const courseFolder = sanitizeName(course?.name ?? enforced?.[2] ?? "Other");
89
+ // Mirror the course's module structure and use the topic's title as the filename
90
+ const location = orgUnitId ? await locateTopic(orgUnitId, fullUrl).catch(() => null) : null;
91
+ const ext = path.extname(urlFilename);
92
+ const filename = location?.title.trim()
93
+ ? sanitizeName(location.title.toLowerCase().endsWith(ext.toLowerCase()) ? location.title : `${location.title}${ext}`)
94
+ : sanitizeName(urlFilename);
95
+ return path.join(getConfig().filesDir, courseFolder, ...(location?.modulePath ?? []).map(sanitizeName), filename);
96
+ };
97
+ const result = await getFile({
98
+ url: fullUrl,
99
+ targetPath: resolveTarget,
100
+ fetch: (headers) => fetchD2L(fullUrl, headers),
101
+ canRevalidate: hasActiveSession,
102
+ refresh,
103
+ });
104
+ const text = await readTextCached(result.path, extractContent);
105
+ return { path: result.path, size: result.size, status: result.status, ...(result.note ? { libraryNote: result.note } : {}), ...page(text) };
106
+ }
107
+ /** A downloaded file by full path, file name, or a unique part of its name. Only library files, so nothing else on disk is exposed. */
108
+ function findLibraryFile(query) {
109
+ const entries = listEntries();
110
+ const exact = entries.find((e) => e.path === query);
111
+ if (exact)
112
+ return exact.path;
113
+ const q = path.basename(query).toLowerCase();
114
+ const byName = entries.filter((e) => path.basename(e.path).toLowerCase() === q);
115
+ const matches = byName.length ? byName : entries.filter((e) => path.basename(e.path).toLowerCase().includes(q));
116
+ if (matches.length === 1)
117
+ return matches[0].path;
118
+ if (matches.length === 0)
119
+ throw new Error(`No downloaded file matches "${query}". Use download_file first.`);
120
+ throw new Error(`"${query}" matches several files: ${matches.slice(0, 8).map((m) => m.path).join("; ")}. Use the full path.`);
121
+ }
122
+ export const downloadFileTool = {
123
+ name: "download_file",
124
+ description: "Download a course file (slides, handouts, assignment PDFs) and return its text. Pass the file URL from get_course_content (e.g. /content/enforced/12345-COURSE/week7.pdf). Files are saved once into the student's course folder and served from disk afterwards. Set refresh=true only if the student says the file changed.",
125
+ schema: {
126
+ url: z.string().describe("File URL or path from get_course_content"),
127
+ refresh: z.boolean().optional().describe("Re-check D2L for a newer version"),
128
+ },
129
+ handler: async (args) => json(await downloadFile(args.url, args.refresh)),
130
+ };
131
+ export const readFileTool = {
132
+ name: "read_file",
133
+ description: "Read the text of a file you already downloaded with download_file, by file name or path. Use offset to continue a long file.",
134
+ schema: {
135
+ file: z.string().describe("File name (or part of it) or full path of a downloaded file"),
136
+ offset: z.coerce.number().min(0).optional().describe("Character offset to continue from"),
137
+ },
138
+ handler: async (args) => {
139
+ const filePath = findLibraryFile(args.file);
140
+ const text = await readTextCached(filePath, extractContent);
141
+ return json({ path: filePath, size: fs.statSync(filePath).size, ...page(text, args.offset) });
142
+ },
143
+ };
@@ -0,0 +1 @@
1
+ export const json = (value) => JSON.stringify(value, null, 2);