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.
- package/LICENSE +23 -0
- package/README.md +87 -2
- package/dist/auth.js +171 -0
- package/dist/browser.js +141 -0
- package/dist/cdp.js +62 -0
- package/dist/cli/manage.js +89 -0
- package/dist/cli/serve.js +84 -0
- package/dist/cli/setup.js +211 -0
- package/dist/cli.js +80 -0
- package/dist/client.js +129 -0
- package/dist/clients/chatgpt.js +30 -0
- package/dist/clients/claudeCode.js +43 -0
- package/dist/clients/claudeDesktop.js +118 -0
- package/dist/clients/self.js +26 -0
- package/dist/config.js +76 -0
- package/dist/courseResolver.js +80 -0
- package/dist/extract.js +60 -0
- package/dist/instructions.js +6 -0
- package/dist/library.js +186 -0
- package/dist/remote/http.js +150 -0
- package/dist/remote/oauth.js +159 -0
- package/dist/remote/service.js +119 -0
- package/dist/remote/tunnel.js +99 -0
- package/dist/schools.js +82 -0
- package/dist/server.js +40 -0
- package/dist/skill.js +2 -0
- package/dist/tools/content.js +24 -0
- package/dist/tools/cooked.js +287 -0
- package/dist/tools/courses.js +28 -0
- package/dist/tools/deadlines.js +59 -0
- package/dist/tools/files.js +143 -0
- package/dist/tools/types.js +1 -0
- package/dist/utils/dateEvent.js +239 -0
- package/dist/utils/marshal.js +247 -0
- package/dist/version.js +2 -0
- package/package.json +54 -4
- package/skill/SKILL.md +58 -0
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
|
+
}
|
package/dist/extract.js
ADDED
|
@@ -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(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/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
|
+
}
|
package/dist/library.js
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import * as http from "http";
|
|
2
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
3
|
+
import { serverInstructions } from "../instructions.js";
|
|
4
|
+
import { createServer } from "../server.js";
|
|
5
|
+
import { OAuthError, OAuthStore } from "./oauth.js";
|
|
6
|
+
export const DEFAULT_PORT = 8787;
|
|
7
|
+
const MAX_BODY = 1024 * 1024;
|
|
8
|
+
const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
9
|
+
function send(res, status, body, headers = {}) {
|
|
10
|
+
const text = typeof body === "string" ? body : JSON.stringify(body);
|
|
11
|
+
res.writeHead(status, {
|
|
12
|
+
"Content-Type": typeof body === "string" ? "text/html; charset=utf-8" : "application/json",
|
|
13
|
+
"Cache-Control": "no-store",
|
|
14
|
+
...headers,
|
|
15
|
+
});
|
|
16
|
+
res.end(text);
|
|
17
|
+
}
|
|
18
|
+
async function readBody(req) {
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
for await (const chunk of req) {
|
|
22
|
+
size += chunk.length;
|
|
23
|
+
if (size > MAX_BODY)
|
|
24
|
+
throw new OAuthError("invalid_request", "Request too large", 413);
|
|
25
|
+
chunks.push(chunk);
|
|
26
|
+
}
|
|
27
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
28
|
+
if (!raw)
|
|
29
|
+
return {};
|
|
30
|
+
if ((req.headers["content-type"] ?? "").includes("application/json"))
|
|
31
|
+
return JSON.parse(raw);
|
|
32
|
+
return Object.fromEntries(new URLSearchParams(raw));
|
|
33
|
+
}
|
|
34
|
+
function consentPage(params, clientName, error) {
|
|
35
|
+
const hidden = ["client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method"]
|
|
36
|
+
.map((k) => `<input type="hidden" name="${k}" value="${escapeHtml(params[k] ?? "")}">`)
|
|
37
|
+
.join("");
|
|
38
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
39
|
+
<title>Connect Am I Cooked</title>
|
|
40
|
+
<style>
|
|
41
|
+
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#F7F3EC;color:#1A1714;font:16px/1.5 system-ui,sans-serif;padding:16px}
|
|
42
|
+
main{max-width:380px;width:100%}h1{font-size:28px;margin:0 0 8px}p{color:#6B645C;margin:0 0 20px}
|
|
43
|
+
input[name=pairing_code]{width:100%;box-sizing:border-box;font:600 28px ui-monospace,monospace;letter-spacing:.3em;text-align:center;padding:12px;border:1px solid #E4DDD2;border-radius:10px;background:#fff}
|
|
44
|
+
button{margin-top:12px;width:100%;padding:12px;border:0;border-radius:10px;background:#1A1714;color:#F7F3EC;font:600 16px system-ui}
|
|
45
|
+
.error{color:#B42318;margin:0 0 12px}code{background:#EFE8DC;padding:1px 5px;border-radius:5px}
|
|
46
|
+
</style></head><body><main>
|
|
47
|
+
<h1>Connect ${escapeHtml(clientName)}</h1>
|
|
48
|
+
<p>Enter the 6-digit code from <code>amicooked pair</code> on your computer. It lets ${escapeHtml(clientName)} read your courses through Am I Cooked.</p>
|
|
49
|
+
${error ? `<p class="error">${escapeHtml(error)}</p>` : ""}
|
|
50
|
+
<form method="post" action="/authorize">${hidden}
|
|
51
|
+
<input name="pairing_code" inputmode="numeric" autocomplete="one-time-code" maxlength="7" required autofocus aria-label="Pairing code">
|
|
52
|
+
<button type="submit">Connect</button></form></main></body></html>`;
|
|
53
|
+
}
|
|
54
|
+
/** HTTP MCP server with OAuth, for ChatGPT and other remote clients. Listens on loopback only. */
|
|
55
|
+
export function createRemoteServer({ publicUrl, store = new OAuthStore() }) {
|
|
56
|
+
const base = publicUrl.replace(/\/+$/, "");
|
|
57
|
+
const resourceMetadata = `${base}/.well-known/oauth-protected-resource`;
|
|
58
|
+
return http.createServer(async (req, res) => {
|
|
59
|
+
const url = new URL(req.url ?? "/", base);
|
|
60
|
+
const route = `${req.method} ${url.pathname}`;
|
|
61
|
+
try {
|
|
62
|
+
if (req.method === "GET" && url.pathname.startsWith("/.well-known/oauth-protected-resource")) {
|
|
63
|
+
return send(res, 200, { resource: `${base}/mcp`, authorization_servers: [base], bearer_methods_supported: ["header"] });
|
|
64
|
+
}
|
|
65
|
+
if (req.method === "GET" && url.pathname.startsWith("/.well-known/oauth-authorization-server")) {
|
|
66
|
+
return send(res, 200, {
|
|
67
|
+
issuer: base,
|
|
68
|
+
authorization_endpoint: `${base}/authorize`,
|
|
69
|
+
token_endpoint: `${base}/token`,
|
|
70
|
+
registration_endpoint: `${base}/register`,
|
|
71
|
+
response_types_supported: ["code"],
|
|
72
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
73
|
+
code_challenge_methods_supported: ["S256"],
|
|
74
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (route === "POST /register") {
|
|
78
|
+
return send(res, 201, { ...store.register(await readBody(req)), token_endpoint_auth_method: "none" });
|
|
79
|
+
}
|
|
80
|
+
if (route === "GET /authorize") {
|
|
81
|
+
const params = Object.fromEntries(url.searchParams);
|
|
82
|
+
if (params.response_type !== "code")
|
|
83
|
+
throw new OAuthError("unsupported_response_type", "Only response_type=code is supported");
|
|
84
|
+
return send(res, 200, consentPage(params, store.clientName(params.client_id, params.redirect_uri)));
|
|
85
|
+
}
|
|
86
|
+
if (route === "POST /authorize") {
|
|
87
|
+
const params = await readBody(req);
|
|
88
|
+
const clientName = store.clientName(params.client_id, params.redirect_uri);
|
|
89
|
+
try {
|
|
90
|
+
const code = store.authorize({
|
|
91
|
+
clientId: params.client_id,
|
|
92
|
+
redirectUri: params.redirect_uri,
|
|
93
|
+
challenge: params.code_challenge,
|
|
94
|
+
method: params.code_challenge_method,
|
|
95
|
+
pairingCode: String(params.pairing_code ?? ""),
|
|
96
|
+
});
|
|
97
|
+
const target = new URL(params.redirect_uri);
|
|
98
|
+
target.searchParams.set("code", code);
|
|
99
|
+
if (params.state)
|
|
100
|
+
target.searchParams.set("state", params.state);
|
|
101
|
+
res.writeHead(302, { Location: target.toString(), "Cache-Control": "no-store" });
|
|
102
|
+
return res.end();
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (!(error instanceof OAuthError) || error.status !== 403)
|
|
106
|
+
throw error;
|
|
107
|
+
return send(res, 403, consentPage(params, clientName, error.message));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (route === "POST /token") {
|
|
111
|
+
const body = await readBody(req);
|
|
112
|
+
if (body.grant_type === "authorization_code") {
|
|
113
|
+
return send(res, 200, store.exchangeCode({ code: body.code, clientId: body.client_id, redirectUri: body.redirect_uri, verifier: body.code_verifier }));
|
|
114
|
+
}
|
|
115
|
+
if (body.grant_type === "refresh_token") {
|
|
116
|
+
return send(res, 200, store.refresh({ refreshToken: body.refresh_token, clientId: body.client_id }));
|
|
117
|
+
}
|
|
118
|
+
throw new OAuthError("unsupported_grant_type", "Use authorization_code or refresh_token");
|
|
119
|
+
}
|
|
120
|
+
if (url.pathname === "/mcp") {
|
|
121
|
+
const auth = req.headers.authorization ?? "";
|
|
122
|
+
if (!auth.startsWith("Bearer ") || !store.verifyAccessToken(auth.slice(7))) {
|
|
123
|
+
return send(res, 401, { error: "invalid_token" }, { "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadata}"` });
|
|
124
|
+
}
|
|
125
|
+
if (req.method !== "POST")
|
|
126
|
+
return send(res, 405, { error: "method_not_allowed" }, { Allow: "POST" });
|
|
127
|
+
// Stateless: a fresh server per request, JSON responses (no SSE, which quick tunnels drop)
|
|
128
|
+
const server = createServer({ instructions: serverInstructions() });
|
|
129
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
130
|
+
res.on("close", () => {
|
|
131
|
+
transport.close().catch(() => { });
|
|
132
|
+
server.close().catch(() => { });
|
|
133
|
+
});
|
|
134
|
+
await server.connect(transport);
|
|
135
|
+
return await transport.handleRequest(req, res, await readBody(req));
|
|
136
|
+
}
|
|
137
|
+
return send(res, 404, { error: "not_found" });
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (res.headersSent)
|
|
141
|
+
return;
|
|
142
|
+
if (error instanceof OAuthError)
|
|
143
|
+
return send(res, error.status, { error: error.code, error_description: error.message });
|
|
144
|
+
if (error instanceof SyntaxError)
|
|
145
|
+
return send(res, 400, { error: "invalid_request", error_description: "Malformed body" });
|
|
146
|
+
console.error(`[http] ${route} failed: ${error instanceof Error ? error.message : error}`);
|
|
147
|
+
return send(res, 500, { error: "server_error" });
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|