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
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from "crypto";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import { paths, writePrivateFile } from "../config.js";
|
|
4
|
+
/**
|
|
5
|
+
* A tiny OAuth 2.1 authorization server for remote MCP clients like ChatGPT:
|
|
6
|
+
* dynamic client registration, authorization code + PKCE (S256), refresh tokens.
|
|
7
|
+
* Consent needs a short pairing code shown on the student's own computer, so
|
|
8
|
+
* someone who finds the public URL can't connect themselves.
|
|
9
|
+
*/
|
|
10
|
+
const ACCESS_TTL_MS = 60 * 60 * 1000;
|
|
11
|
+
const REFRESH_TTL_MS = 90 * 24 * 60 * 60 * 1000;
|
|
12
|
+
const CODE_TTL_MS = 5 * 60 * 1000;
|
|
13
|
+
const PAIRING_TTL_MS = 10 * 60 * 1000;
|
|
14
|
+
const PAIRING_MAX_ATTEMPTS = 5;
|
|
15
|
+
export class OAuthError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
status;
|
|
18
|
+
constructor(code, message, status = 400) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.status = status;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
25
|
+
const b64url = (buf) => buf.toString("base64url");
|
|
26
|
+
const secret = () => b64url(randomBytes(32));
|
|
27
|
+
function sameHash(a, b) {
|
|
28
|
+
const x = Buffer.from(a, "hex");
|
|
29
|
+
const y = Buffer.from(b, "hex");
|
|
30
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
31
|
+
}
|
|
32
|
+
/** Redirects must go to an https URL (or loopback during development). */
|
|
33
|
+
function validRedirect(uri) {
|
|
34
|
+
try {
|
|
35
|
+
const u = new URL(uri);
|
|
36
|
+
return u.protocol === "https:" || (u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname));
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class OAuthStore {
|
|
43
|
+
file;
|
|
44
|
+
now;
|
|
45
|
+
constructor(file = paths().oauth, now = () => Date.now()) {
|
|
46
|
+
this.file = file;
|
|
47
|
+
this.now = now;
|
|
48
|
+
}
|
|
49
|
+
load() {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(fs.readFileSync(this.file, "utf8"));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return { clients: {}, codes: {}, tokens: {} };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
save(state) {
|
|
58
|
+
const t = this.now();
|
|
59
|
+
// Drop anything expired so the file doesn't grow forever
|
|
60
|
+
for (const [k, v] of Object.entries(state.codes))
|
|
61
|
+
if (v.expiresAt < t)
|
|
62
|
+
delete state.codes[k];
|
|
63
|
+
for (const [k, v] of Object.entries(state.tokens))
|
|
64
|
+
if (v.expiresAt < t)
|
|
65
|
+
delete state.tokens[k];
|
|
66
|
+
writePrivateFile(this.file, JSON.stringify(state));
|
|
67
|
+
}
|
|
68
|
+
/** A fresh 6-digit pairing code for the student to type into ChatGPT's consent page. */
|
|
69
|
+
newPairingCode() {
|
|
70
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
|
71
|
+
const state = this.load();
|
|
72
|
+
state.pairing = { hash: sha256(code), expiresAt: this.now() + PAIRING_TTL_MS, attempts: 0 };
|
|
73
|
+
this.save(state);
|
|
74
|
+
return code;
|
|
75
|
+
}
|
|
76
|
+
register(body) {
|
|
77
|
+
const uris = Array.isArray(body.redirect_uris) ? body.redirect_uris.filter((u) => typeof u === "string") : [];
|
|
78
|
+
if (!uris.length || !uris.every(validRedirect))
|
|
79
|
+
throw new OAuthError("invalid_redirect_uri", "redirect_uris must be https URLs");
|
|
80
|
+
const state = this.load();
|
|
81
|
+
if (Object.keys(state.clients).length >= 50)
|
|
82
|
+
throw new OAuthError("invalid_client_metadata", "Too many registered clients");
|
|
83
|
+
const id = secret();
|
|
84
|
+
const name = (body.client_name ?? "AI app").slice(0, 80);
|
|
85
|
+
state.clients[id] = { name, redirectUris: uris, createdAt: this.now() };
|
|
86
|
+
this.save(state);
|
|
87
|
+
return { client_id: id, client_name: name, redirect_uris: uris };
|
|
88
|
+
}
|
|
89
|
+
clientName(clientId, redirectUri) {
|
|
90
|
+
const client = this.load().clients[clientId];
|
|
91
|
+
if (!client)
|
|
92
|
+
throw new OAuthError("invalid_client", "Unknown client");
|
|
93
|
+
if (!client.redirectUris.includes(redirectUri))
|
|
94
|
+
throw new OAuthError("invalid_request", "redirect_uri doesn't match the registration");
|
|
95
|
+
return client.name;
|
|
96
|
+
}
|
|
97
|
+
/** Check the pairing code and issue an authorization code bound to the PKCE challenge. */
|
|
98
|
+
authorize(params) {
|
|
99
|
+
this.clientName(params.clientId, params.redirectUri);
|
|
100
|
+
if (params.method !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(params.challenge)) {
|
|
101
|
+
throw new OAuthError("invalid_request", "PKCE with S256 is required");
|
|
102
|
+
}
|
|
103
|
+
const state = this.load();
|
|
104
|
+
const pairing = state.pairing;
|
|
105
|
+
if (!pairing || pairing.expiresAt < this.now() || pairing.attempts >= PAIRING_MAX_ATTEMPTS) {
|
|
106
|
+
throw new OAuthError("access_denied", "That pairing code expired. Run `amicooked pair` for a new one.", 403);
|
|
107
|
+
}
|
|
108
|
+
if (!sameHash(sha256(params.pairingCode.replace(/\D/g, "")), pairing.hash)) {
|
|
109
|
+
pairing.attempts++;
|
|
110
|
+
this.save(state);
|
|
111
|
+
throw new OAuthError("access_denied", "Wrong pairing code. Check the code from `amicooked pair`.", 403);
|
|
112
|
+
}
|
|
113
|
+
delete state.pairing; // one use
|
|
114
|
+
const code = secret();
|
|
115
|
+
state.codes[sha256(code)] = { clientId: params.clientId, redirectUri: params.redirectUri, challenge: params.challenge, expiresAt: this.now() + CODE_TTL_MS };
|
|
116
|
+
this.save(state);
|
|
117
|
+
return code;
|
|
118
|
+
}
|
|
119
|
+
issue(state, clientId) {
|
|
120
|
+
const access = secret();
|
|
121
|
+
const refresh = secret();
|
|
122
|
+
state.tokens[sha256(access)] = { clientId, kind: "access", expiresAt: this.now() + ACCESS_TTL_MS };
|
|
123
|
+
state.tokens[sha256(refresh)] = { clientId, kind: "refresh", expiresAt: this.now() + REFRESH_TTL_MS };
|
|
124
|
+
this.save(state);
|
|
125
|
+
return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_MS / 1000, refresh_token: refresh };
|
|
126
|
+
}
|
|
127
|
+
exchangeCode(params) {
|
|
128
|
+
const state = this.load();
|
|
129
|
+
const key = sha256(params.code);
|
|
130
|
+
const grant = state.codes[key];
|
|
131
|
+
delete state.codes[key]; // codes are single-use even when the exchange fails
|
|
132
|
+
this.save(state);
|
|
133
|
+
if (!grant || grant.expiresAt < this.now())
|
|
134
|
+
throw new OAuthError("invalid_grant", "Authorization code is invalid or expired");
|
|
135
|
+
if (grant.clientId !== params.clientId || grant.redirectUri !== params.redirectUri)
|
|
136
|
+
throw new OAuthError("invalid_grant", "Code was issued to another client");
|
|
137
|
+
if (b64url(createHash("sha256").update(params.verifier).digest()) !== grant.challenge)
|
|
138
|
+
throw new OAuthError("invalid_grant", "PKCE verification failed");
|
|
139
|
+
return this.issue(this.load(), grant.clientId);
|
|
140
|
+
}
|
|
141
|
+
refresh(params) {
|
|
142
|
+
const state = this.load();
|
|
143
|
+
const key = sha256(params.refreshToken);
|
|
144
|
+
const token = state.tokens[key];
|
|
145
|
+
if (!token || token.kind !== "refresh" || token.expiresAt < this.now() || token.clientId !== params.clientId) {
|
|
146
|
+
throw new OAuthError("invalid_grant", "Refresh token is invalid or expired");
|
|
147
|
+
}
|
|
148
|
+
delete state.tokens[key]; // rotate
|
|
149
|
+
return this.issue(state, token.clientId);
|
|
150
|
+
}
|
|
151
|
+
verifyAccessToken(token) {
|
|
152
|
+
const entry = this.load().tokens[sha256(token)];
|
|
153
|
+
return Boolean(entry && entry.kind === "access" && entry.expiresAt > this.now());
|
|
154
|
+
}
|
|
155
|
+
/** Disconnect every remote app, e.g. when the student turns ChatGPT off. */
|
|
156
|
+
revokeAll() {
|
|
157
|
+
this.save({ clients: {}, codes: {}, tokens: {} });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
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 { paths } from "../config.js";
|
|
6
|
+
/**
|
|
7
|
+
* Keeps `amicooked serve` running in the student's login session, so ChatGPT can reach
|
|
8
|
+
* it whenever the computer is on: a LaunchAgent on macOS, a logon task on Windows,
|
|
9
|
+
* a systemd user unit on Linux.
|
|
10
|
+
*/
|
|
11
|
+
const LABEL = "app.amicooked.serve";
|
|
12
|
+
const TASK = "Am I Cooked";
|
|
13
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
14
|
+
export function launchAgentPlist(launch, logFile) {
|
|
15
|
+
const args = [launch.command, ...launch.args].map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
16
|
+
const env = Object.entries(launch.env ?? {})
|
|
17
|
+
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
18
|
+
.join("\n");
|
|
19
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
20
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
21
|
+
<plist version="1.0">
|
|
22
|
+
<dict>
|
|
23
|
+
<key>Label</key>
|
|
24
|
+
<string>${LABEL}</string>
|
|
25
|
+
<key>ProgramArguments</key>
|
|
26
|
+
<array>
|
|
27
|
+
${args}
|
|
28
|
+
</array>
|
|
29
|
+
${env ? ` <key>EnvironmentVariables</key>\n <dict>\n${env}\n </dict>\n` : ""} <key>RunAtLoad</key>
|
|
30
|
+
<true/>
|
|
31
|
+
<key>KeepAlive</key>
|
|
32
|
+
<true/>
|
|
33
|
+
<key>StandardOutPath</key>
|
|
34
|
+
<string>${xml(logFile)}</string>
|
|
35
|
+
<key>StandardErrorPath</key>
|
|
36
|
+
<string>${xml(logFile)}</string>
|
|
37
|
+
</dict>
|
|
38
|
+
</plist>
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
export function systemdUnit(launch) {
|
|
42
|
+
const quote = (a) => (/[\s"\\]/.test(a) ? `"${a.replace(/(["\\])/g, "\\$1")}"` : a);
|
|
43
|
+
const env = Object.entries(launch.env ?? {}).map(([k, v]) => `Environment=${quote(`${k}=${v}`)}\n`).join("");
|
|
44
|
+
return `[Unit]
|
|
45
|
+
Description=Am I Cooked (ChatGPT connection)
|
|
46
|
+
After=network-online.target
|
|
47
|
+
|
|
48
|
+
[Service]
|
|
49
|
+
ExecStart=${[launch.command, ...launch.args].map(quote).join(" ")}
|
|
50
|
+
${env}Restart=always
|
|
51
|
+
RestartSec=10
|
|
52
|
+
|
|
53
|
+
[Install]
|
|
54
|
+
WantedBy=default.target
|
|
55
|
+
`;
|
|
56
|
+
}
|
|
57
|
+
/** Windows runs console programs in a visible window; a VBScript wrapper starts it hidden. */
|
|
58
|
+
export function hiddenLauncherVbs(launch) {
|
|
59
|
+
const cmd = [launch.command, ...launch.args].map((a) => `""${a}""`).join(" ");
|
|
60
|
+
return `CreateObject("Wscript.Shell").Run "${cmd}", 0, False\r\n`;
|
|
61
|
+
}
|
|
62
|
+
function run(cmd, args) {
|
|
63
|
+
const result = spawnSync(cmd, args, { encoding: "utf8" });
|
|
64
|
+
if (result.error || result.status !== 0) {
|
|
65
|
+
throw new Error(`${cmd} ${args[0]} failed: ${(result.stderr || result.error?.message || "").trim()}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const plistPath = () => path.join(os.homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
69
|
+
const unitPath = () => path.join(os.homedir(), ".config", "systemd", "user", "amicooked.service");
|
|
70
|
+
const vbsPath = () => path.join(paths().bin, "amicooked-serve.vbs");
|
|
71
|
+
/** Install (or replace) the background service running `launch`, and start it now. */
|
|
72
|
+
export function installService(launch) {
|
|
73
|
+
fs.mkdirSync(paths().logs, { recursive: true });
|
|
74
|
+
if (process.platform === "darwin") {
|
|
75
|
+
const uid = String(os.userInfo().uid);
|
|
76
|
+
fs.mkdirSync(path.dirname(plistPath()), { recursive: true });
|
|
77
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plistPath()]);
|
|
78
|
+
fs.writeFileSync(plistPath(), launchAgentPlist(launch, path.join(paths().logs, "serve.log")));
|
|
79
|
+
run("launchctl", ["bootstrap", `gui/${uid}`, plistPath()]);
|
|
80
|
+
}
|
|
81
|
+
else if (process.platform === "win32") {
|
|
82
|
+
fs.mkdirSync(paths().bin, { recursive: true });
|
|
83
|
+
fs.writeFileSync(vbsPath(), hiddenLauncherVbs(launch));
|
|
84
|
+
run("schtasks", ["/Create", "/F", "/TN", TASK, "/SC", "ONLOGON", "/RL", "LIMITED", "/TR", `wscript.exe "${vbsPath()}"`]);
|
|
85
|
+
run("schtasks", ["/Run", "/TN", TASK]);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
fs.mkdirSync(path.dirname(unitPath()), { recursive: true });
|
|
89
|
+
fs.writeFileSync(unitPath(), systemdUnit(launch));
|
|
90
|
+
run("systemctl", ["--user", "daemon-reload"]);
|
|
91
|
+
run("systemctl", ["--user", "enable", "--now", "amicooked.service"]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function uninstallService() {
|
|
95
|
+
if (process.platform === "darwin") {
|
|
96
|
+
if (!fs.existsSync(plistPath()))
|
|
97
|
+
return false;
|
|
98
|
+
spawnSync("launchctl", ["bootout", `gui/${os.userInfo().uid}`, plistPath()]);
|
|
99
|
+
fs.rmSync(plistPath());
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
if (process.platform === "win32") {
|
|
103
|
+
const result = spawnSync("schtasks", ["/Delete", "/F", "/TN", TASK]);
|
|
104
|
+
fs.rmSync(vbsPath(), { force: true });
|
|
105
|
+
return result.status === 0;
|
|
106
|
+
}
|
|
107
|
+
if (!fs.existsSync(unitPath()))
|
|
108
|
+
return false;
|
|
109
|
+
spawnSync("systemctl", ["--user", "disable", "--now", "amicooked.service"]);
|
|
110
|
+
fs.rmSync(unitPath());
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
export function serviceInstalled() {
|
|
114
|
+
if (process.platform === "darwin")
|
|
115
|
+
return fs.existsSync(plistPath());
|
|
116
|
+
if (process.platform === "win32")
|
|
117
|
+
return spawnSync("schtasks", ["/Query", "/TN", TASK]).status === 0;
|
|
118
|
+
return fs.existsSync(unitPath());
|
|
119
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { execFileSync, spawn, spawnSync } from "child_process";
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as os from "os";
|
|
5
|
+
import * as path from "path";
|
|
6
|
+
import { paths, writePrivateFile } from "../config.js";
|
|
7
|
+
import { VERSION } from "../version.js";
|
|
8
|
+
/** Hands out a permanent <id>.amicooked.app tunnel; holds the Cloudflare API token so we never ship it. */
|
|
9
|
+
const TUNNEL_API = process.env.AMICOOKED_TUNNEL_API || "https://tunnels.amicooked.app";
|
|
10
|
+
const USER_AGENT = `amicooked/${VERSION}`;
|
|
11
|
+
export function readTunnel() {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(fs.readFileSync(paths().tunnel, "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Reuse this computer's tunnel, or ask the provisioning API for one. */
|
|
20
|
+
export async function ensureTunnel() {
|
|
21
|
+
const existing = readTunnel();
|
|
22
|
+
if (existing)
|
|
23
|
+
return existing;
|
|
24
|
+
const res = await fetch(`${TUNNEL_API}/tunnels`, { method: "POST", headers: { "User-Agent": USER_AGENT }, signal: AbortSignal.timeout(30000) });
|
|
25
|
+
if (res.status === 429)
|
|
26
|
+
throw new Error("Too many ChatGPT connections were set up from this network today. Try again tomorrow.");
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
throw new Error(`Couldn't set up the ChatGPT connection (error ${res.status}). Try again later.`);
|
|
29
|
+
const body = (await res.json());
|
|
30
|
+
const tunnel = { url: body.url, tunnelId: body.tunnelId, tunnelToken: body.tunnelToken, heartbeatSecret: body.heartbeatSecret };
|
|
31
|
+
writePrivateFile(paths().tunnel, JSON.stringify(tunnel));
|
|
32
|
+
return tunnel;
|
|
33
|
+
}
|
|
34
|
+
/** Tell the API this tunnel is still in use, so it isn't cleaned up after 30 quiet days. */
|
|
35
|
+
export async function heartbeat(tunnel) {
|
|
36
|
+
await fetch(`${TUNNEL_API}/tunnels/heartbeat`, {
|
|
37
|
+
method: "POST",
|
|
38
|
+
headers: { "User-Agent": USER_AGENT, Authorization: `Bearer ${tunnel.heartbeatSecret}`, "Content-Type": "application/json" },
|
|
39
|
+
body: JSON.stringify({ tunnelId: tunnel.tunnelId }),
|
|
40
|
+
signal: AbortSignal.timeout(15000),
|
|
41
|
+
}).catch(() => { });
|
|
42
|
+
}
|
|
43
|
+
// ---- cloudflared ----
|
|
44
|
+
const CLOUDFLARED_VERSION = "2026.10.3";
|
|
45
|
+
// SHA-256 of each release asset as downloaded (GitHub's asset digest; the release notes hash the binary inside the .tgz)
|
|
46
|
+
const CLOUDFLARED_ASSETS = {
|
|
47
|
+
"darwin-arm64": { asset: "cloudflared-darwin-arm64.tgz", sha256: "1165d14b6f6360a3b8c283d7d1100024d6ec7cd9bc9e32519e96150645f3ec55" },
|
|
48
|
+
"darwin-x64": { asset: "cloudflared-darwin-amd64.tgz", sha256: "81b7b85f2376815c4f59b1aa323887b62e16ce8b67555c2e1577dc23f2a82000" },
|
|
49
|
+
"linux-x64": { asset: "cloudflared-linux-amd64", sha256: "053b80b0a23031a038fdbf3c073f59f82b8f1f152aa67971d7383ffafc0dbab0" },
|
|
50
|
+
"win32-x64": { asset: "cloudflared-windows-amd64.exe", sha256: "76b2805253d0d6ffacb092a7acfbee99e7af6917835c0c5410e23f3ef5052da2" },
|
|
51
|
+
};
|
|
52
|
+
const exe = process.platform === "win32" ? "cloudflared.exe" : "cloudflared";
|
|
53
|
+
/** A cloudflared to run: one already on PATH, or our own pinned, checksum-verified copy. */
|
|
54
|
+
export async function ensureCloudflared() {
|
|
55
|
+
const onPath = spawnSync("cloudflared", ["--version"], { encoding: "utf8", shell: process.platform === "win32" });
|
|
56
|
+
if (!onPath.error && onPath.status === 0)
|
|
57
|
+
return "cloudflared";
|
|
58
|
+
const target = path.join(paths().bin, exe);
|
|
59
|
+
if (fs.existsSync(target))
|
|
60
|
+
return target;
|
|
61
|
+
const key = `${process.platform}-${os.arch()}`;
|
|
62
|
+
const spec = CLOUDFLARED_ASSETS[key];
|
|
63
|
+
if (!spec)
|
|
64
|
+
throw new Error(`ChatGPT support isn't available on ${key} yet.`);
|
|
65
|
+
const url = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${spec.asset}`;
|
|
66
|
+
// GitHub's download CDN sometimes answers 5xx; retry a couple of times before giving up
|
|
67
|
+
let res = null;
|
|
68
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
69
|
+
res = await fetch(url, { signal: AbortSignal.timeout(120000) }).catch(() => null);
|
|
70
|
+
if (res?.ok)
|
|
71
|
+
break;
|
|
72
|
+
await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
|
|
73
|
+
}
|
|
74
|
+
if (!res?.ok)
|
|
75
|
+
throw new Error(`Couldn't download cloudflared (${res?.status ?? "network error"}). Check your connection and try again.`);
|
|
76
|
+
const data = Buffer.from(await res.arrayBuffer());
|
|
77
|
+
if (createHash("sha256").update(data).digest("hex") !== spec.sha256)
|
|
78
|
+
throw new Error("cloudflared download failed its checksum; not using it.");
|
|
79
|
+
fs.mkdirSync(paths().bin, { recursive: true });
|
|
80
|
+
if (spec.asset.endsWith(".tgz")) {
|
|
81
|
+
const archive = path.join(paths().bin, spec.asset);
|
|
82
|
+
fs.writeFileSync(archive, data);
|
|
83
|
+
execFileSync("tar", ["-xzf", archive, "-C", paths().bin]);
|
|
84
|
+
fs.rmSync(archive);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
fs.writeFileSync(target, data);
|
|
88
|
+
}
|
|
89
|
+
fs.chmodSync(target, 0o755);
|
|
90
|
+
return target;
|
|
91
|
+
}
|
|
92
|
+
/** Run the tunnel. The token goes through the environment so it isn't visible in `ps`. */
|
|
93
|
+
export function startCloudflared(binary, tunnel) {
|
|
94
|
+
return spawn(binary, ["tunnel", "--no-autoupdate", "run"], {
|
|
95
|
+
env: { ...process.env, TUNNEL_TOKEN: tunnel.tunnelToken },
|
|
96
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
97
|
+
windowsHide: true,
|
|
98
|
+
});
|
|
99
|
+
}
|
package/dist/schools.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** API versions the tools are written against. Setup checks the school supports them. */
|
|
2
|
+
export const API_VERSIONS = { le: "1.57", lp: "1.43" };
|
|
3
|
+
/** Ontario Brightspace schools, hosts checked against /d2l/api/versions/. Only McMaster is login-tested. */
|
|
4
|
+
export const PRESETS = [
|
|
5
|
+
{ id: "mcmaster", name: "McMaster University", lmsName: "Avenue to Learn", host: "avenue.cllmcmaster.ca", loginUrl: "https://avenue.mcmaster.ca/login.php" },
|
|
6
|
+
{ id: "waterloo", name: "University of Waterloo", lmsName: "LEARN", host: "learn.uwaterloo.ca" },
|
|
7
|
+
{ id: "western", name: "Western University", lmsName: "OWL Brightspace", host: "westernu.brightspace.com" },
|
|
8
|
+
{ id: "queens", name: "Queen's University", lmsName: "onQ", host: "onq.queensu.ca" },
|
|
9
|
+
{ id: "guelph", name: "University of Guelph", lmsName: "CourseLink", host: "courselink.uoguelph.ca" },
|
|
10
|
+
{ id: "laurier", name: "Wilfrid Laurier University", lmsName: "MyLearningSpace", host: "mylearningspace.wlu.ca" },
|
|
11
|
+
{ id: "tmu", name: "Toronto Metropolitan University", lmsName: "D2L Brightspace", host: "courses.torontomu.ca" },
|
|
12
|
+
{ id: "uottawa", name: "University of Ottawa", lmsName: "Brightspace", host: "uottawa.brightspace.com" },
|
|
13
|
+
{ id: "carleton", name: "Carleton University", lmsName: "Brightspace", host: "brightspace.carleton.ca" },
|
|
14
|
+
{ id: "brock", name: "Brock University", lmsName: "Brightspace", host: "brightspace.brocku.ca" },
|
|
15
|
+
{ id: "windsor", name: "University of Windsor", lmsName: "Brightspace", host: "brightspace.uwindsor.ca" },
|
|
16
|
+
{ id: "laurentian", name: "Laurentian University", lmsName: "D2L", host: "d2l.laurentian.ca" },
|
|
17
|
+
{ id: "lakehead", name: "Lakehead University", lmsName: "myCourseLink", host: "mycourselink.lakeheadu.ca" },
|
|
18
|
+
];
|
|
19
|
+
export function findPreset(id) {
|
|
20
|
+
const key = id.trim().toLowerCase();
|
|
21
|
+
return PRESETS.find((s) => s.id === key || s.host === key);
|
|
22
|
+
}
|
|
23
|
+
/** True if `host` serves the Brightspace versions API with the versions we need. */
|
|
24
|
+
export async function checkBrightspaceHost(host, fetchImpl = fetch) {
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetchImpl(`https://${host}/d2l/api/versions/`, { signal: AbortSignal.timeout(10000) });
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
return false;
|
|
29
|
+
const products = (await res.json());
|
|
30
|
+
const supports = (code) => products.some((p) => p.ProductCode === code && p.SupportedVersions.includes(API_VERSIONS[code]));
|
|
31
|
+
return supports("le") && supports("lp");
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function normalizeUrl(input) {
|
|
38
|
+
const trimmed = input.trim();
|
|
39
|
+
return new URL(/^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
|
|
40
|
+
}
|
|
41
|
+
/** Hosts of absolute links into /d2l/ found in a page, e.g. an SSO portal linking to the real D2L host. */
|
|
42
|
+
function d2lHostsIn(html) {
|
|
43
|
+
const hosts = [...html.matchAll(/https:\/\/([a-z0-9.-]+)\/d2l\//gi)].map((m) => m[1].toLowerCase());
|
|
44
|
+
return [...new Set(hosts)];
|
|
45
|
+
}
|
|
46
|
+
async function fetchPage(url, fetchImpl) {
|
|
47
|
+
try {
|
|
48
|
+
const res = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(10000) });
|
|
49
|
+
return { finalHost: new URL(res.url || url).host, html: await res.text() };
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Work out the school from whatever URL a student logs in through: the D2L host itself,
|
|
57
|
+
* a page that redirects there, or a portal that links to it.
|
|
58
|
+
*/
|
|
59
|
+
export async function detectSchool(input, fetchImpl = fetch) {
|
|
60
|
+
const url = normalizeUrl(input);
|
|
61
|
+
const preset = PRESETS.find((s) => s.host === url.host || (s.loginUrl && new URL(s.loginUrl).host === url.host));
|
|
62
|
+
if (preset)
|
|
63
|
+
return preset;
|
|
64
|
+
const candidates = [url.host];
|
|
65
|
+
for (const pageUrl of [url.href, url.origin + "/"]) {
|
|
66
|
+
const page = await fetchPage(pageUrl, fetchImpl);
|
|
67
|
+
if (page)
|
|
68
|
+
candidates.push(page.finalHost, ...d2lHostsIn(page.html));
|
|
69
|
+
}
|
|
70
|
+
for (const host of [...new Set(candidates)]) {
|
|
71
|
+
if (await checkBrightspaceHost(host, fetchImpl)) {
|
|
72
|
+
return {
|
|
73
|
+
id: "custom",
|
|
74
|
+
name: host,
|
|
75
|
+
lmsName: "D2L",
|
|
76
|
+
host,
|
|
77
|
+
...(host !== url.host ? { loginUrl: url.href } : {}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`Couldn't find D2L Brightspace at ${url.host}. Log in to your school's D2L in a browser and paste the address of your course homepage (it contains /d2l/home).`);
|
|
82
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { LoginPendingError } from "./auth.js";
|
|
3
|
+
import { amICookedTool } from "./tools/cooked.js";
|
|
4
|
+
import { getAnnouncements, getMyCourses, getMyGrades } from "./tools/courses.js";
|
|
5
|
+
import { getCourseContent } from "./tools/content.js";
|
|
6
|
+
import { getAssignments, getUpcomingDueDates } from "./tools/deadlines.js";
|
|
7
|
+
import { downloadFileTool, readFileTool } from "./tools/files.js";
|
|
8
|
+
import { VERSION } from "./version.js";
|
|
9
|
+
export const TOOLS = [
|
|
10
|
+
amICookedTool,
|
|
11
|
+
getMyCourses,
|
|
12
|
+
getMyGrades,
|
|
13
|
+
getUpcomingDueDates,
|
|
14
|
+
getAnnouncements,
|
|
15
|
+
getAssignments,
|
|
16
|
+
getCourseContent,
|
|
17
|
+
downloadFileTool,
|
|
18
|
+
readFileTool,
|
|
19
|
+
];
|
|
20
|
+
export function createServer(options = {}) {
|
|
21
|
+
const server = new McpServer({ name: "amicooked", version: VERSION }, { instructions: options.instructions });
|
|
22
|
+
for (const tool of TOOLS) {
|
|
23
|
+
server.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema, annotations: { readOnlyHint: true, openWorldHint: false } }, async (args) => {
|
|
24
|
+
const started = Date.now();
|
|
25
|
+
try {
|
|
26
|
+
const text = await tool.handler(args ?? {});
|
|
27
|
+
console.error(`[tool] ${tool.name} ok (${Date.now() - started}ms)`);
|
|
28
|
+
return { content: [{ type: "text", text }] };
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
32
|
+
console.error(`[tool] ${tool.name} failed (${Date.now() - started}ms): ${message}`);
|
|
33
|
+
// Report errors as results so the AI can relay them, e.g. "sign in, then ask again"
|
|
34
|
+
const text = error instanceof LoginPendingError ? message : `Error: ${message}`;
|
|
35
|
+
return { content: [{ type: "text", text }], isError: true };
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return server;
|
|
40
|
+
}
|
package/dist/skill.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated from skill/SKILL.md by scripts/sync-skill.mjs. Don't edit by hand.
|
|
2
|
+
export const SKILL_MD = "---\nname: amicooked\ndescription: Use when a student asks about their D2L Brightspace courses, grades, deadlines, assignments, announcements or course files, asks \"am I cooked?\", or wants to set up Am I Cooked.\n---\n\n# Am I Cooked\n\nAm I Cooked connects an AI assistant to a student's D2L Brightspace account (Avenue to Learn, LEARN, onQ, OWL Brightspace, CourseLink, MyLearningSpace and others). It runs on the student's own computer and is read-only.\n\n## Setting it up (for agents)\n\n1. Ask the student which school they go to. Presets: mcmaster, waterloo, western, queens, guelph, laurier, tmu, uottawa, carleton, brock, windsor, laurentian, lakehead. Any other Brightspace school works with the URL they log in through.\n2. Install it:\n - macOS / Linux: `curl -fsSL https://amicooked-mcp.vercel.app/install.sh | sh -s -- --no-setup`\n - Windows (PowerShell): `$env:AMICOOKED_NO_SETUP=1; irm https://amicooked-mcp.vercel.app/install.ps1 | iex`\n - With Node.js installed, `npx -y amicooked@0` works in place of `amicooked` below.\n3. Run setup with flags, and a long command timeout (at least 5 minutes), because the student signs in through a browser window that opens:\n `amicooked setup --school mcmaster --clients desktop,code`\n Use `--school https://...` for schools without a preset. Add `chatgpt` to `--clients` if they use ChatGPT.\n4. Tell the student to sign in to their school in the browser window. Never ask for their password; you never need it.\n5. If something fails, run `amicooked status` and read what it says.\n\n<!-- server-instructions -->\n## Answering questions\n\n- Start broad questions (\"am I cooked?\", \"what should I work on?\", \"how am I doing?\", \"what's due?\") with `am_i_cooked`. It covers every current course in one call.\n- Other tools take a course code directly, like `course: \"3BB4\"`. Only call `get_my_courses` when a code is ambiguous or the student asks what they're enrolled in.\n- Check `get_announcements` for a course before a final verdict on it; deadlines and exam details often change there.\n- To read slides, handouts or assignment PDFs: `get_course_content` to find the file, then `download_file`. Use `read_file` for files already downloaded.\n- If a tool says a login window opened, tell the student to sign in there and ask again.\n\n## The verdict\n\nUse `summary.heatLabel` from `am_i_cooked` to set the tone. Be playful, never mean, and always useful.\n\n| heatLabel | Tone |\n|---|---|\n| raw | Relaxed. Nothing urgent; maybe get ahead on something. |\n| warming up | Light nudge. One or two things to handle soon. |\n| toasty | Focused. A real plan for the next few days. |\n| cooked | Direct and supportive. Triage what matters most. |\n| well done | Calm and practical. Damage control, and who to talk to. |\n\n1. Lead with a one-line verdict, e.g. \"Toasty, not cooked.\"\n2. Then the top 3 actions, each with course, item and due time in the student's local time (D2L times are UTC).\n3. Say whether a grade is `final_calculated` or `estimated_from_items`; estimates ignore dropped and bonus items.\n - For an estimate, say how much is left, like \"67.6% so far. 60% of your grade is still to come.\" Use `weightRemaining` for that number.\n - Name the `keyItems` when a grade needs explaining, with their weight: \"the midterm (59.5%, worth 25%) is pulling it down.\"\n - Never work weights out backwards from a result. Use the `weight` values the tools return.\n - `basis: \"points\"` means the gradebook has no weights. Say the estimate is by points and the real weighting may differ. If the student asks how the grade is calculated, find the course outline with `get_course_content` and read the weights from it.\n4. `late_window_open` means a missed assignment can still be submitted: say so first, it's the easiest win.\n5. If `partial_data` appears, mention that some of a course couldn't be loaded.\n6. For grades under 60%, suggest office hours, the TA, or an academic advisor.\n\n## Integrity\n\nAm I Cooked only reads. Help the student understand material and plan their time, but don't write graded work for them to submit.\n<!-- /server-instructions -->\n";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { client } from "../client.js";
|
|
3
|
+
import { courseParams, resolveCourse } from "../courseResolver.js";
|
|
4
|
+
import { marshalContentModule, marshalToc, marshalTopic, } from "../utils/marshal.js";
|
|
5
|
+
import { json } from "./types.js";
|
|
6
|
+
export const getCourseContent = {
|
|
7
|
+
name: "get_course_content",
|
|
8
|
+
description: "A course's content: modules, lectures, readings and files with their IDs. With no IDs you get the whole outline; pass moduleId to open one section, or topicId for one item's details and URL (then use download_file to read it).",
|
|
9
|
+
schema: {
|
|
10
|
+
...courseParams,
|
|
11
|
+
moduleId: z.coerce.number().optional().describe("Open one module/section from the outline"),
|
|
12
|
+
topicId: z.coerce.number().optional().describe("Details for one topic (lecture, file, link)"),
|
|
13
|
+
},
|
|
14
|
+
handler: async (args) => {
|
|
15
|
+
const orgUnitId = await resolveCourse(args);
|
|
16
|
+
if (args.topicId) {
|
|
17
|
+
return json(marshalTopic((await client.getContentTopic(orgUnitId, args.topicId))));
|
|
18
|
+
}
|
|
19
|
+
if (args.moduleId) {
|
|
20
|
+
return json(marshalContentModule((await client.getContentModule(orgUnitId, args.moduleId))));
|
|
21
|
+
}
|
|
22
|
+
return json(marshalToc((await client.getContentToc(orgUnitId))));
|
|
23
|
+
},
|
|
24
|
+
};
|