amicooked 0.0.0-stage → 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.
@@ -0,0 +1,117 @@
1
+ import { spawnSync } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as os from "os";
4
+ import * as path from "path";
5
+ import { SKILL_MD } from "../skill.js";
6
+ import { SERVER_NAME } from "./claudeDesktop.js";
7
+ const currentEnv = () => ({ platform: process.platform, home: os.homedir(), codexHome: process.env.CODEX_HOME });
8
+ export const codexHome = (env = currentEnv()) => env.codexHome || path.join(env.home, ".codex");
9
+ export const codexConfigPath = (env = currentEnv()) => path.join(codexHome(env), "config.toml");
10
+ /** macOS app bundles that are the Codex-based desktop app, under either name. */
11
+ const MAC_APPS = ["/Applications/ChatGPT.app", "/Applications/Codex.app"];
12
+ function isCodexBundle(app) {
13
+ const plist = path.join(app, "Contents", "Info.plist");
14
+ if (!fs.existsSync(plist))
15
+ return false;
16
+ const id = spawnSync("/usr/libexec/PlistBuddy", ["-c", "Print :CFBundleIdentifier", plist], { encoding: "utf8" });
17
+ return id.status === 0 && id.stdout.trim() === "com.openai.codex";
18
+ }
19
+ /** True when the ChatGPT desktop app (or Codex) is on this computer. */
20
+ export function hasCodex(env = currentEnv(), hasMacApp = () => MAC_APPS.some(isCodexBundle)) {
21
+ if (fs.existsSync(codexHome(env)))
22
+ return true;
23
+ return env.platform === "darwin" && hasMacApp();
24
+ }
25
+ // ---- config.toml, edited as text so every other setting stays byte for byte ----
26
+ const TABLE = `mcp_servers.${SERVER_NAME}`;
27
+ const header = (line) => line.match(/^\s*\[\s*([^\]]+?)\s*\]\s*(#.*)?$/)?.[1] ?? null;
28
+ /** Splits the file into our table (and its sub-tables, like `.env`) and everything else. */
29
+ function splitOurTable(text) {
30
+ const kept = [];
31
+ const ours = [];
32
+ // Comments and blank lines after our table usually belong to the table that follows, so they
33
+ // wait here until we know which side they're on
34
+ let pending = [];
35
+ let inOurs = false;
36
+ for (const line of text.split("\n")) {
37
+ const name = header(line);
38
+ if (name !== null) {
39
+ kept.push(...pending);
40
+ pending = [];
41
+ inOurs = name === TABLE || name.startsWith(`${TABLE}.`);
42
+ (inOurs ? ours : kept).push(line);
43
+ }
44
+ else if (inOurs && /^\s*(#.*)?$/.test(line)) {
45
+ pending.push(line);
46
+ }
47
+ else {
48
+ if (inOurs)
49
+ ours.push(...pending);
50
+ else
51
+ kept.push(...pending);
52
+ pending = [];
53
+ (inOurs ? ours : kept).push(line);
54
+ }
55
+ }
56
+ kept.push(...pending);
57
+ return { rest: kept.join("\n"), ours: ours.length ? ours.join("\n").trim() : null };
58
+ }
59
+ /** TOML basic strings use the same escapes as JSON for everything we'd ever write. */
60
+ const str = (s) => JSON.stringify(s);
61
+ export function tomlEntry(launch) {
62
+ const lines = [`[${TABLE}]`, `command = ${str(launch.command)}`, `args = [${launch.args.map(str).join(", ")}]`];
63
+ if (launch.env && Object.keys(launch.env).length) {
64
+ lines.push("", `[${TABLE}.env]`, ...Object.entries(launch.env).map(([k, v]) => `${k} = ${str(v)}`));
65
+ }
66
+ return lines.join("\n");
67
+ }
68
+ function writeAtomic(file, text) {
69
+ fs.mkdirSync(path.dirname(file), { recursive: true });
70
+ const backup = `${file}.amicooked.bak`;
71
+ if (fs.existsSync(file) && !fs.existsSync(backup))
72
+ fs.copyFileSync(file, backup);
73
+ const tmp = `${file}.${process.pid}.tmp`;
74
+ fs.writeFileSync(tmp, text);
75
+ fs.renameSync(tmp, file);
76
+ }
77
+ /** Add or update our server in config.toml. Re-running changes nothing; other servers are untouched. */
78
+ export function installCodex(launch, file = codexConfigPath()) {
79
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
80
+ const { rest, ours } = splitOurTable(text);
81
+ const entry = tomlEntry(launch);
82
+ if (ours === entry)
83
+ return "unchanged";
84
+ const body = rest.replace(/\s+$/, "");
85
+ writeAtomic(file, `${body ? `${body}\n\n` : ""}${entry}\n`);
86
+ return ours ? "updated" : "added";
87
+ }
88
+ export function uninstallCodex(file = codexConfigPath()) {
89
+ if (!fs.existsSync(file))
90
+ return "absent";
91
+ const { rest, ours } = splitOurTable(fs.readFileSync(file, "utf8"));
92
+ if (!ours)
93
+ return "absent";
94
+ writeAtomic(file, `${rest.replace(/\s+$/, "")}\n`);
95
+ return "removed";
96
+ }
97
+ export function codexConfigured(file = codexConfigPath()) {
98
+ return fs.existsSync(file) && splitOurTable(fs.readFileSync(file, "utf8")).ours !== null;
99
+ }
100
+ // ---- the skill: the desktop app reads skills from ~/.agents/skills ----
101
+ export const codexSkillPath = (home = os.homedir()) => path.join(home, ".agents", "skills", SERVER_NAME, "SKILL.md");
102
+ export function installCodexSkill(home = os.homedir()) {
103
+ const file = codexSkillPath(home);
104
+ const existed = fs.existsSync(file);
105
+ if (existed && fs.readFileSync(file, "utf8") === SKILL_MD)
106
+ return "unchanged";
107
+ fs.mkdirSync(path.dirname(file), { recursive: true });
108
+ fs.writeFileSync(file, SKILL_MD);
109
+ return existed ? "updated" : "added";
110
+ }
111
+ export function uninstallCodexSkill(home = os.homedir()) {
112
+ const dir = path.dirname(codexSkillPath(home));
113
+ if (!fs.existsSync(dir))
114
+ return "absent";
115
+ fs.rmSync(dir, { recursive: true, force: true });
116
+ return "removed";
117
+ }
@@ -0,0 +1,26 @@
1
+ import * as path from "path";
2
+ function currentRuntime() {
3
+ // Bun-compiled binaries run their bundled script from a virtual /$bunfs (B:/~BUN on Windows) path
4
+ const script = process.argv[1] ?? "";
5
+ const isCompiled = script.includes("$bunfs") || script.includes("~BUN");
6
+ return { execPath: process.execPath, argv: process.argv, platform: process.platform, isCompiled };
7
+ }
8
+ /**
9
+ * How an AI app should start this same install of Am I Cooked, plus `extraArgs`.
10
+ * Configs must keep working after this process exits, so npx's temporary cache
11
+ * is never referenced directly.
12
+ */
13
+ export function selfCommand(extraArgs, rt = currentRuntime()) {
14
+ if (rt.isCompiled)
15
+ return { command: rt.execPath, args: extraArgs };
16
+ const script = rt.argv[1] ?? "";
17
+ const viaNpx = /[\\/]_npx[\\/]/.test(script);
18
+ if (!viaNpx)
19
+ return { command: rt.execPath, args: [script, ...extraArgs] };
20
+ const pkg = ["-y", "amicooked@0", ...extraArgs];
21
+ if (rt.platform === "win32")
22
+ return { command: "cmd", args: ["/c", "npx", ...pkg] };
23
+ // GUI apps don't inherit the shell's PATH (nvm, Homebrew), and npx's shebang needs `node` on it
24
+ const binDir = path.posix.dirname(rt.execPath);
25
+ return { command: path.posix.join(binDir, "npx"), args: pkg, env: { PATH: `${binDir}:/usr/bin:/bin` } };
26
+ }
package/dist/config.js ADDED
@@ -0,0 +1,76 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+ export function homeDir() {
5
+ return process.env.AMICOOKED_HOME || path.join(os.homedir(), ".amicooked");
6
+ }
7
+ export function paths() {
8
+ const home = homeDir();
9
+ return {
10
+ home,
11
+ config: path.join(home, "config.json"),
12
+ browser: path.join(home, "browser"),
13
+ token: path.join(home, "token.json"),
14
+ library: path.join(home, "library.json"),
15
+ textCache: path.join(home, "text-cache"),
16
+ oauth: path.join(home, "oauth.json"),
17
+ tunnel: path.join(home, "tunnel.json"),
18
+ bin: path.join(home, "bin"),
19
+ logs: path.join(home, "logs"),
20
+ };
21
+ }
22
+ function defaults() {
23
+ return { version: 1, filesDir: path.join(os.homedir(), "Downloads", "amicooked") };
24
+ }
25
+ let cached = null;
26
+ function readFile() {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(paths().config, "utf8"));
29
+ }
30
+ catch (error) {
31
+ if (error.code === "ENOENT")
32
+ return {};
33
+ throw new Error(`Couldn't read ${paths().config}: ${error.message}`);
34
+ }
35
+ }
36
+ /** Config file merged over defaults, with D2L_HOST / D2L_LOGIN_URL env vars on top. */
37
+ export function getConfig() {
38
+ if (cached)
39
+ return cached;
40
+ const config = { ...defaults(), ...readFile(), version: 1 };
41
+ const host = process.env.D2L_HOST;
42
+ if (host) {
43
+ config.school = {
44
+ ...(config.school?.host === host ? config.school : { id: "custom", name: host, lmsName: "D2L" }),
45
+ host,
46
+ };
47
+ }
48
+ if (process.env.D2L_LOGIN_URL && config.school) {
49
+ config.school = { ...config.school, loginUrl: process.env.D2L_LOGIN_URL };
50
+ }
51
+ cached = config;
52
+ return config;
53
+ }
54
+ export function reloadConfig() {
55
+ cached = null;
56
+ return getConfig();
57
+ }
58
+ /** The configured school, or a clear error telling the student to run setup. */
59
+ export function getSchool() {
60
+ const school = getConfig().school;
61
+ if (!school)
62
+ throw new Error("Am I Cooked isn't set up yet. Run `amicooked setup` first.");
63
+ return school;
64
+ }
65
+ /** Write a file atomically with owner-only permissions. */
66
+ export function writePrivateFile(file, contents) {
67
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
68
+ const tmp = `${file}.${process.pid}.tmp`;
69
+ fs.writeFileSync(tmp, contents, { mode: 0o600 });
70
+ fs.renameSync(tmp, file);
71
+ }
72
+ export function writeConfig(update) {
73
+ const next = { ...defaults(), ...readFile(), ...update, version: 1 };
74
+ writePrivateFile(paths().config, JSON.stringify(next, null, 2) + "\n");
75
+ return reloadConfig();
76
+ }
@@ -0,0 +1,80 @@
1
+ import { z } from "zod";
2
+ import { client } from "./client.js";
3
+ /** Zod fields every per-course tool accepts: a course code/name, or the D2L org unit ID. */
4
+ export const courseParams = {
5
+ course: z.string().optional().describe('Course code or name, e.g. "3BB4" or "Software Design". Preferred over orgUnitId.'),
6
+ orgUnitId: z.coerce.number().optional().describe("D2L org unit ID of the course, if you already have it"),
7
+ };
8
+ const CACHE_MS = 5 * 60 * 1000;
9
+ let cache = null;
10
+ /** Course offerings the student can open, cached for a few minutes. */
11
+ export async function listCourses() {
12
+ if (cache && Date.now() - cache.at < CACHE_MS)
13
+ return cache.courses;
14
+ const { Items } = (await client.getMyEnrollments());
15
+ const courses = Items.filter((e) => e.OrgUnit.Type.Code === "Course Offering" && e.Access.CanAccess).map((e) => ({
16
+ id: e.OrgUnit.Id,
17
+ name: e.OrgUnit.Name,
18
+ code: e.OrgUnit.Code,
19
+ isActive: e.Access.IsActive,
20
+ lastAccessed: e.Access.LastAccessed,
21
+ endDate: e.Access.EndDate ?? null,
22
+ pinned: Boolean(e.PinDate),
23
+ }));
24
+ cache = { at: Date.now(), courses };
25
+ return courses;
26
+ }
27
+ const DAY = 24 * 60 * 60 * 1000;
28
+ /**
29
+ * This term's courses: active, not ended more than two weeks ago, and opened recently.
30
+ * D2L usually leaves term dates empty and pins outlive their term, so recency does the
31
+ * work: the last six weeks, widening to four months (e.g. over a break) if that's empty.
32
+ */
33
+ export function currentCourses(courses, now = Date.now()) {
34
+ const active = courses.filter((c) => c.isActive && (!c.endDate || Date.parse(c.endDate) > now - 14 * DAY));
35
+ const openedWithin = (days) => active.filter((c) => c.lastAccessed && Date.parse(c.lastAccessed) > now - days * DAY);
36
+ for (const days of [42, 120]) {
37
+ const recent = openedWithin(days);
38
+ if (recent.length)
39
+ return recent;
40
+ }
41
+ return active;
42
+ }
43
+ export function clearCourseCache() {
44
+ cache = null;
45
+ }
46
+ const tokens = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
47
+ /** Courses matching `query`: exact ID, then a code token like "3BB4", then a name substring. */
48
+ export function matchCourses(courses, query) {
49
+ const q = query.trim().toLowerCase();
50
+ if (/^\d+$/.test(q)) {
51
+ const byId = courses.filter((c) => String(c.id) === q);
52
+ if (byId.length)
53
+ return byId;
54
+ }
55
+ const qTokens = tokens(q);
56
+ const byCode = courses.filter((c) => {
57
+ const codeTokens = [...tokens(c.code), ...tokens(c.name)];
58
+ return qTokens.every((t) => codeTokens.includes(t));
59
+ });
60
+ if (byCode.length)
61
+ return byCode;
62
+ return courses.filter((c) => c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q));
63
+ }
64
+ /** Resolve a tool's `course` / `orgUnitId` arguments to one org unit ID. */
65
+ export async function resolveCourse(args) {
66
+ if (args.orgUnitId)
67
+ return args.orgUnitId;
68
+ if (!args.course)
69
+ throw new Error('Say which course, e.g. course: "3BB4". Use get_my_courses to list them.');
70
+ const matches = matchCourses(await listCourses(), args.course);
71
+ // Prefer current courses when an old offering of the same course also matches
72
+ const active = matches.filter((c) => c.isActive);
73
+ const pool = active.length ? active : matches;
74
+ if (pool.length === 1)
75
+ return pool[0].id;
76
+ if (pool.length === 0)
77
+ throw new Error(`No course matches "${args.course}". Use get_my_courses to list them.`);
78
+ const list = pool.slice(0, 8).map((c) => `${c.code} (${c.name}, id ${c.id})`).join("; ");
79
+ throw new Error(`"${args.course}" matches several courses: ${list}. Use a more specific code or the orgUnitId.`);
80
+ }
@@ -0,0 +1,60 @@
1
+ import JSZip from "jszip";
2
+ import mammoth from "mammoth";
3
+ import { extractText, getDocumentProxy } from "unpdf";
4
+ const TEXT_EXTENSIONS = new Set([
5
+ ".txt", ".md", ".csv", ".json", ".xml", ".html", ".htm", ".css",
6
+ ".js", ".ts", ".py", ".java", ".c", ".cpp", ".h", ".tex", ".sql",
7
+ ]);
8
+ const decodeXml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
9
+ /** Text of a PowerPoint XML part: <a:t> runs, one line per <a:p> paragraph, minus slide-number placeholders. */
10
+ function slideXmlText(xml) {
11
+ return xml
12
+ .split(/<\/a:p>/)
13
+ .map((para) => decodeXml([...para.matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((m) => m[1]).join("")).trim())
14
+ .filter((line) => line && !/^\d+$/.test(line))
15
+ .join("\n");
16
+ }
17
+ async function pptxText(data) {
18
+ const zip = await JSZip.loadAsync(data);
19
+ const slideNumber = (name) => Number(name.match(/(\d+)\.xml$/)?.[1] ?? 0);
20
+ const slides = Object.keys(zip.files)
21
+ .filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name))
22
+ .sort((a, b) => slideNumber(a) - slideNumber(b));
23
+ const parts = [];
24
+ for (const name of slides) {
25
+ const n = slideNumber(name);
26
+ let text = slideXmlText(await zip.file(name).async("string"));
27
+ const notes = zip.file(`ppt/notesSlides/notesSlide${n}.xml`);
28
+ if (notes) {
29
+ const notesText = slideXmlText(await notes.async("string"));
30
+ if (notesText)
31
+ text += `\n[Notes] ${notesText}`;
32
+ }
33
+ parts.push(`--- Slide ${n} ---\n${text || "(no text, likely a diagram or image)"}`);
34
+ }
35
+ return parts.length ? parts.join("\n\n") : null;
36
+ }
37
+ async function pdfText(data) {
38
+ const pdf = await getDocumentProxy(new Uint8Array(data));
39
+ const { text } = await extractText(pdf, { mergePages: false });
40
+ const pages = text.map((page, i) => `--- Page ${i + 1} ---\n${page.trim()}`);
41
+ return pages.length ? pages.join("\n\n") : null;
42
+ }
43
+ /** Plain text from a course file, or null for formats we can't read (images, old .doc, ...). */
44
+ export async function extractContent(data, ext) {
45
+ const lower = ext.toLowerCase();
46
+ try {
47
+ if (TEXT_EXTENSIONS.has(lower))
48
+ return data.toString("utf-8");
49
+ if (lower === ".docx")
50
+ return (await mammoth.extractRawText({ buffer: data })).value.trim() || null;
51
+ if (lower === ".pptx" || lower === ".ppsx")
52
+ return await pptxText(data);
53
+ if (lower === ".pdf")
54
+ return await pdfText(data);
55
+ }
56
+ catch (error) {
57
+ console.error(`[extract] couldn't read ${lower} file: ${error instanceof Error ? error.message : error}`);
58
+ }
59
+ return null;
60
+ }
@@ -0,0 +1,6 @@
1
+ import { SKILL_MD } from "./skill.js";
2
+ /** The part of SKILL.md meant for any AI using the tools, sent as the MCP server instructions. */
3
+ export function serverInstructions() {
4
+ const match = SKILL_MD.match(/<!-- server-instructions -->([\s\S]*?)<!-- \/server-instructions -->/);
5
+ return (match?.[1] ?? "").trim();
6
+ }
@@ -0,0 +1,186 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { paths } from './config.js';
5
+ /**
6
+ * Local file library: every downloaded course file is recorded in a manifest
7
+ * keyed by source URL, so asking for the same file again is served from disk.
8
+ *
9
+ * - Cached files are re-checked with a conditional request (ETag/Last-Modified,
10
+ * a few ms, no body) at most every REVALIDATE_MS, or when refresh is requested.
11
+ * - A file the user has changed locally (e.g. annotated) is never overwritten;
12
+ * a newer server version is saved next to it instead.
13
+ * - Concurrent requests for the same URL share a single download.
14
+ */
15
+ const REVALIDATE_MS = 12 * 60 * 60 * 1000;
16
+ const REVALIDATE_TIMEOUT_MS = 10_000;
17
+ // Bump when text extraction changes so cached text is regenerated
18
+ const TEXT_CACHE_VERSION = 2;
19
+ // ---- manifest persistence (read-modify-write, serialized within the process) ----
20
+ let writeChain = Promise.resolve();
21
+ function readManifest() {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(paths().library, 'utf8'));
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ function updateManifest(mutate) {
30
+ const next = writeChain.then(() => {
31
+ const manifest = readManifest();
32
+ mutate(manifest);
33
+ const manifestPath = paths().library;
34
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
35
+ const tmp = `${manifestPath}.${process.pid}.tmp`;
36
+ fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2));
37
+ fs.renameSync(tmp, manifestPath);
38
+ });
39
+ writeChain = next.catch(() => { });
40
+ return next;
41
+ }
42
+ // ---- helpers ----
43
+ function writeAtomic(filePath, data) {
44
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
+ const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.part`);
46
+ fs.writeFileSync(tmp, data);
47
+ fs.renameSync(tmp, filePath);
48
+ return fs.statSync(filePath);
49
+ }
50
+ /** Append " (2)", " (3)"... until the path is free on disk and not claimed by another URL. */
51
+ function uniquePath(desired, manifest, url) {
52
+ const claimed = new Set(Object.entries(manifest).filter(([u]) => u !== url).map(([, e]) => e.path));
53
+ const ext = path.extname(desired);
54
+ const base = desired.slice(0, desired.length - ext.length);
55
+ let candidate = desired;
56
+ for (let n = 2; fs.existsSync(candidate) || claimed.has(candidate); n++) {
57
+ candidate = `${base} (${n})${ext}`;
58
+ }
59
+ return candidate;
60
+ }
61
+ function isLocallyModified(entry, stat) {
62
+ return stat.size !== entry.size || Math.abs(stat.mtimeMs - entry.mtimeMs) > 2000;
63
+ }
64
+ function validators(res) {
65
+ return {
66
+ etag: res.headers.get('etag') || undefined,
67
+ lastModified: res.headers.get('last-modified') || undefined,
68
+ contentType: res.headers.get('content-type')?.split(';')[0] || undefined,
69
+ };
70
+ }
71
+ async function withTimeout(promise, ms) {
72
+ let timer;
73
+ try {
74
+ return await Promise.race([
75
+ promise,
76
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms); }),
77
+ ]);
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ }
82
+ }
83
+ // ---- main entry point ----
84
+ const inFlight = new Map();
85
+ export function getFile(req) {
86
+ const existing = inFlight.get(req.url);
87
+ if (existing)
88
+ return existing;
89
+ const promise = resolveFile(req).finally(() => inFlight.delete(req.url));
90
+ inFlight.set(req.url, promise);
91
+ return promise;
92
+ }
93
+ async function resolveFile(req) {
94
+ const now = new Date();
95
+ const entry = readManifest()[req.url];
96
+ const stat = entry && fs.existsSync(entry.path) ? fs.statSync(entry.path) : null;
97
+ if (entry && stat) {
98
+ const cached = { path: entry.path, status: 'cached', size: stat.size, contentType: entry.contentType };
99
+ const stale = req.refresh || now.getTime() - Date.parse(entry.checkedAt) > REVALIDATE_MS;
100
+ if (!stale)
101
+ return cached;
102
+ if (!req.canRevalidate())
103
+ return { ...cached, note: 'Served from disk; not re-checked for updates (not signed in yet).' };
104
+ let res;
105
+ try {
106
+ const headers = {};
107
+ if (entry.etag)
108
+ headers['If-None-Match'] = entry.etag;
109
+ if (entry.lastModified)
110
+ headers['If-Modified-Since'] = entry.lastModified;
111
+ res = await withTimeout(req.fetch(headers), REVALIDATE_TIMEOUT_MS);
112
+ }
113
+ catch (error) {
114
+ return { ...cached, note: `Served from disk; update check failed (${error instanceof Error ? error.message : error}).` };
115
+ }
116
+ if (res.status === 304) {
117
+ await updateManifest((m) => { if (m[req.url])
118
+ m[req.url].checkedAt = now.toISOString(); });
119
+ return cached;
120
+ }
121
+ const data = Buffer.from(await res.arrayBuffer());
122
+ const meta = validators(res);
123
+ // Some servers ignore conditional headers; identical bytes means nothing changed
124
+ if (!isLocallyModified(entry, stat) && data.length === stat.size && data.equals(fs.readFileSync(entry.path))) {
125
+ await updateManifest((m) => { if (m[req.url])
126
+ Object.assign(m[req.url], meta, { checkedAt: now.toISOString() }); });
127
+ return cached;
128
+ }
129
+ let savePath = entry.path;
130
+ let status = 'updated';
131
+ if (isLocallyModified(entry, stat)) {
132
+ // Keep the user's edited copy; put the new version beside it
133
+ const ext = path.extname(entry.path);
134
+ const dated = `${entry.path.slice(0, entry.path.length - ext.length)} (updated ${now.toISOString().slice(0, 10)})${ext}`;
135
+ savePath = uniquePath(dated, readManifest(), req.url);
136
+ status = 'updated-alongside';
137
+ }
138
+ const newStat = writeAtomic(savePath, data);
139
+ await updateManifest((m) => {
140
+ m[req.url] = { path: savePath, ...meta, size: newStat.size, mtimeMs: newStat.mtimeMs, downloadedAt: now.toISOString(), checkedAt: now.toISOString() };
141
+ });
142
+ return {
143
+ path: savePath, status, size: newStat.size, contentType: meta.contentType,
144
+ note: status === 'updated-alongside' ? `Your modified copy was kept at ${entry.path}.` : undefined,
145
+ };
146
+ }
147
+ // Not downloaded yet (or the local file was deleted): download it
148
+ const targetPath = entry ? entry.path : await req.targetPath();
149
+ const res = await req.fetch({});
150
+ const data = Buffer.from(await res.arrayBuffer());
151
+ const meta = validators(res);
152
+ // An identical file already at the target (e.g. the manifest was lost) is adopted, not duplicated
153
+ const adoptable = !entry && fs.existsSync(targetPath)
154
+ && !Object.entries(readManifest()).some(([u, e]) => u !== req.url && e.path === targetPath)
155
+ && fs.readFileSync(targetPath).equals(data);
156
+ const savePath = entry || adoptable ? targetPath : uniquePath(targetPath, readManifest(), req.url);
157
+ const newStat = adoptable ? fs.statSync(savePath) : writeAtomic(savePath, data);
158
+ await updateManifest((m) => {
159
+ m[req.url] = { path: savePath, ...meta, size: newStat.size, mtimeMs: newStat.mtimeMs, downloadedAt: now.toISOString(), checkedAt: now.toISOString() };
160
+ });
161
+ return { path: savePath, status: 'downloaded', size: newStat.size, contentType: meta.contentType };
162
+ }
163
+ /** Every downloaded file still on disk, for finding a file by name later. */
164
+ export function listEntries() {
165
+ return Object.entries(readManifest())
166
+ .filter(([, e]) => fs.existsSync(e.path))
167
+ .map(([url, e]) => ({ url, path: e.path, downloadedAt: e.downloadedAt }));
168
+ }
169
+ /**
170
+ * Extract text from a library file, caching the result keyed by path + size + mtime
171
+ * so large PDFs are only parsed once.
172
+ */
173
+ export async function readTextCached(filePath, extract) {
174
+ const stat = fs.statSync(filePath);
175
+ const key = crypto.createHash('sha1').update(`v${TEXT_CACHE_VERSION}|${filePath}|${stat.size}|${stat.mtimeMs}`).digest('hex');
176
+ const cacheDir = paths().textCache;
177
+ const cachePath = path.join(cacheDir, `${key}.txt`);
178
+ if (fs.existsSync(cachePath))
179
+ return fs.readFileSync(cachePath, 'utf8');
180
+ const text = await extract(fs.readFileSync(filePath), path.extname(filePath));
181
+ if (text !== null) {
182
+ fs.mkdirSync(cacheDir, { recursive: true });
183
+ fs.writeFileSync(cachePath, text);
184
+ }
185
+ return text;
186
+ }