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,211 @@
|
|
|
1
|
+
import * as p from "@clack/prompts";
|
|
2
|
+
import { hasActiveSession, login } from "../auth.js";
|
|
3
|
+
import { detectChannel } from "../browser.js";
|
|
4
|
+
import { claudeDesktopDir, installClaudeDesktop, InvalidConfigError, isClaudeDesktopRunning, manualSnippet, openClaudeDesktop, quitClaudeDesktop, } from "../clients/claudeDesktop.js";
|
|
5
|
+
import { hasClaudeCode, installClaudeCode, installSkill } from "../clients/claudeCode.js";
|
|
6
|
+
import { chatgptSteps, installChatGPT } from "../clients/chatgpt.js";
|
|
7
|
+
import { selfCommand } from "../clients/self.js";
|
|
8
|
+
import { client } from "../client.js";
|
|
9
|
+
import { getConfig, writeConfig } from "../config.js";
|
|
10
|
+
import { listCourses } from "../courseResolver.js";
|
|
11
|
+
import { detectSchool, findPreset, PRESETS } from "../schools.js";
|
|
12
|
+
import { amICooked } from "../tools/cooked.js";
|
|
13
|
+
const CLIENT_IDS = ["desktop", "code", "chatgpt"];
|
|
14
|
+
/** Exit code for "the agent needs to ask the student something first". */
|
|
15
|
+
export const NEEDS_INPUT = 2;
|
|
16
|
+
class SetupStop extends Error {
|
|
17
|
+
code;
|
|
18
|
+
constructor(message, code = 1) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.code = code;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
24
|
+
function presetList() {
|
|
25
|
+
return PRESETS.map((s) => ` ${s.id.padEnd(11)} ${s.name} (${s.lmsName})`).join("\n");
|
|
26
|
+
}
|
|
27
|
+
async function chooseSchool(flag) {
|
|
28
|
+
if (flag)
|
|
29
|
+
return findPreset(flag) ?? (await detectSchool(flag));
|
|
30
|
+
const current = getConfig().school;
|
|
31
|
+
if (!interactive()) {
|
|
32
|
+
if (current)
|
|
33
|
+
return current;
|
|
34
|
+
throw new SetupStop(`Which school? Ask the student, then run setup again with --school <id> or --school <the URL they log in through>.\n\nPresets:\n${presetList()}`, NEEDS_INPUT);
|
|
35
|
+
}
|
|
36
|
+
const choice = await p.select({
|
|
37
|
+
message: "Which school do you go to?",
|
|
38
|
+
initialValue: current?.id === "custom" ? "other" : current?.id,
|
|
39
|
+
options: [
|
|
40
|
+
...PRESETS.map((s) => ({ value: s.id, label: s.name, hint: s.lmsName })),
|
|
41
|
+
{ value: "other", label: "Somewhere else", hint: "paste the URL you log in through" },
|
|
42
|
+
],
|
|
43
|
+
});
|
|
44
|
+
if (p.isCancel(choice))
|
|
45
|
+
throw new SetupStop("Setup cancelled.");
|
|
46
|
+
if (choice !== "other")
|
|
47
|
+
return findPreset(choice);
|
|
48
|
+
const url = await p.text({
|
|
49
|
+
message: "Paste the web address you use to log in to your courses",
|
|
50
|
+
placeholder: "https://learn.myschool.edu",
|
|
51
|
+
validate: (v) => (v?.trim() ? undefined : "Paste a URL"),
|
|
52
|
+
});
|
|
53
|
+
if (p.isCancel(url))
|
|
54
|
+
throw new SetupStop("Setup cancelled.");
|
|
55
|
+
const spin = p.spinner();
|
|
56
|
+
spin.start("Finding your school's Brightspace");
|
|
57
|
+
try {
|
|
58
|
+
const school = await detectSchool(url);
|
|
59
|
+
spin.stop(`Found ${school.host}`);
|
|
60
|
+
return school;
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
spin.stop("Couldn't find it");
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function chooseClients(flag, detected, yes) {
|
|
68
|
+
if (flag) {
|
|
69
|
+
const ids = flag.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
70
|
+
const unknown = ids.filter((id) => !CLIENT_IDS.includes(id));
|
|
71
|
+
if (unknown.length)
|
|
72
|
+
throw new SetupStop(`Unknown app: ${unknown.join(", ")}. Use desktop, code or chatgpt.`);
|
|
73
|
+
return ids;
|
|
74
|
+
}
|
|
75
|
+
const defaults = CLIENT_IDS.filter((id) => detected[id]);
|
|
76
|
+
if (yes || !interactive())
|
|
77
|
+
return defaults;
|
|
78
|
+
const chosen = await p.multiselect({
|
|
79
|
+
message: "Where do you want to use it?",
|
|
80
|
+
initialValues: defaults,
|
|
81
|
+
required: false,
|
|
82
|
+
options: [
|
|
83
|
+
{ value: "desktop", label: "Claude Desktop", hint: detected.desktop ? "found" : "not found" },
|
|
84
|
+
{ value: "code", label: "Claude Code", hint: detected.code ? "found" : "not found" },
|
|
85
|
+
{ value: "chatgpt", label: "ChatGPT", hint: "runs in the background while your computer is on" },
|
|
86
|
+
],
|
|
87
|
+
});
|
|
88
|
+
if (p.isCancel(chosen))
|
|
89
|
+
throw new SetupStop("Setup cancelled.");
|
|
90
|
+
return chosen;
|
|
91
|
+
}
|
|
92
|
+
/** Claude Desktop saves its own config over ours when it quits, so it has to be closed before we write. */
|
|
93
|
+
async function closeClaudeDesktop() {
|
|
94
|
+
if (!isClaudeDesktopRunning())
|
|
95
|
+
return "not_running";
|
|
96
|
+
// An agent may be running this from inside Claude Desktop; never close it without asking
|
|
97
|
+
if (!interactive())
|
|
98
|
+
return "left_open";
|
|
99
|
+
const ok = await p.confirm({ message: "Claude Desktop is open and has to restart to pick this up. Quit it now? It reopens when setup is done." });
|
|
100
|
+
if (p.isCancel(ok) || !ok)
|
|
101
|
+
return "left_open";
|
|
102
|
+
return (await quitClaudeDesktop()) ? "closed" : "left_open";
|
|
103
|
+
}
|
|
104
|
+
async function configureClients(clients) {
|
|
105
|
+
const done = [];
|
|
106
|
+
const launch = selfCommand(["mcp"]);
|
|
107
|
+
if (clients.includes("desktop")) {
|
|
108
|
+
const dir = claudeDesktopDir();
|
|
109
|
+
if (!dir) {
|
|
110
|
+
p.log.warn("Claude Desktop isn't installed. Get it at https://claude.ai/download, then run `amicooked setup` again.");
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
try {
|
|
114
|
+
const state = await closeClaudeDesktop();
|
|
115
|
+
const result = installClaudeDesktop(dir, launch);
|
|
116
|
+
if (state === "left_open" && result !== "unchanged") {
|
|
117
|
+
// Written, but the open app will save its own copy over it when it quits
|
|
118
|
+
p.log.warn("Claude Desktop is open, so it will undo this when it quits. Quit it, then run `amicooked setup --clients desktop`.");
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
p.log.success(`Claude Desktop: ${result === "unchanged" ? "already set up" : "set up"}`);
|
|
122
|
+
done.push(state === "closed" && openClaudeDesktop() ? "desktop-reopened" : "desktop");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (!(error instanceof InvalidConfigError))
|
|
127
|
+
throw error;
|
|
128
|
+
p.log.warn(`${error.message}\nAdd this to it yourself:\n${manualSnippet(launch)}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (clients.includes("code")) {
|
|
133
|
+
if (!hasClaudeCode()) {
|
|
134
|
+
p.log.warn("Claude Code isn't installed, so it was skipped.");
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
installClaudeCode(launch);
|
|
138
|
+
installSkill();
|
|
139
|
+
p.log.success("Claude Code: set up, with the amicooked skill");
|
|
140
|
+
done.push("code");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (clients.includes("chatgpt")) {
|
|
144
|
+
const spin = p.spinner();
|
|
145
|
+
spin.start("Setting up your private ChatGPT connection");
|
|
146
|
+
try {
|
|
147
|
+
const { url, pairingCode } = await installChatGPT();
|
|
148
|
+
spin.stop("ChatGPT: running in the background");
|
|
149
|
+
p.note(chatgptSteps(url, pairingCode), "Connect ChatGPT");
|
|
150
|
+
done.push("chatgpt");
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
spin.stop(`ChatGPT: ${error instanceof Error ? error.message : error}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return done;
|
|
157
|
+
}
|
|
158
|
+
async function firstRoast() {
|
|
159
|
+
const spin = p.spinner();
|
|
160
|
+
spin.start("Checking whether you're cooked");
|
|
161
|
+
try {
|
|
162
|
+
const report = await amICooked({});
|
|
163
|
+
const { heat, heatLabel, dueSoon, overdue } = report.summary;
|
|
164
|
+
spin.stop(`Heat: ${heatLabel} (${heat}/10) · ${dueSoon} due this week${overdue ? ` · ${overdue} overdue` : ""}`);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
spin.stop(`Couldn't build your first report: ${error instanceof Error ? error.message : error}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export async function setup(options) {
|
|
171
|
+
p.intro("Am I Cooked");
|
|
172
|
+
try {
|
|
173
|
+
const school = await chooseSchool(options.school);
|
|
174
|
+
p.log.info(`School: ${school.name} (${school.host})`);
|
|
175
|
+
const browser = getConfig().browser ?? (await detectChannel());
|
|
176
|
+
if (!browser) {
|
|
177
|
+
throw new SetupStop("Am I Cooked logs in through Google Chrome or Microsoft Edge. Install one of them, then run setup again.");
|
|
178
|
+
}
|
|
179
|
+
const schoolChanged = getConfig().school?.host !== school.host;
|
|
180
|
+
writeConfig({ school, browser });
|
|
181
|
+
if (options.login !== false && (schoolChanged || !hasActiveSession())) {
|
|
182
|
+
p.log.step("A browser window is opening. Sign in to your school there; this window waits for you.");
|
|
183
|
+
await login();
|
|
184
|
+
}
|
|
185
|
+
if (options.login !== false) {
|
|
186
|
+
const me = (await client.whoami());
|
|
187
|
+
const courses = await listCourses();
|
|
188
|
+
p.log.success(`Signed in${me.FirstName ? ` as ${me.FirstName}` : ""}. Found ${courses.length} course${courses.length === 1 ? "" : "s"}.`);
|
|
189
|
+
}
|
|
190
|
+
const detected = { desktop: Boolean(claudeDesktopDir()), code: hasClaudeCode(), chatgpt: false };
|
|
191
|
+
const done = await configureClients(await chooseClients(options.clients, detected, Boolean(options.yes)));
|
|
192
|
+
if (options.login !== false)
|
|
193
|
+
await firstRoast();
|
|
194
|
+
const next = done.includes("desktop-reopened")
|
|
195
|
+
? "Claude Desktop is reopening. Ask it: am I cooked?"
|
|
196
|
+
: done.includes("desktop")
|
|
197
|
+
? "Open Claude Desktop and ask: am I cooked?"
|
|
198
|
+
: done.includes("code")
|
|
199
|
+
? "Start Claude Code and ask: am I cooked?"
|
|
200
|
+
: done.includes("chatgpt")
|
|
201
|
+
? "Finish connecting in ChatGPT, then ask: am I cooked?"
|
|
202
|
+
: "Run `amicooked setup` again once you've installed Claude Desktop, Claude Code or ChatGPT.";
|
|
203
|
+
p.outro(next);
|
|
204
|
+
return 0;
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
const code = error instanceof SetupStop ? error.code : 1;
|
|
208
|
+
p.cancel(error instanceof Error ? error.message : String(error));
|
|
209
|
+
return code;
|
|
210
|
+
}
|
|
211
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "util";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { loginCommand, pairCommand, statusCommand, uninstallCommand } from "./cli/manage.js";
|
|
5
|
+
import { serveCommand } from "./cli/serve.js";
|
|
6
|
+
import { setup } from "./cli/setup.js";
|
|
7
|
+
import { serverInstructions } from "./instructions.js";
|
|
8
|
+
import { createServer } from "./server.js";
|
|
9
|
+
import { VERSION } from "./version.js";
|
|
10
|
+
const HELP = `Am I Cooked ${VERSION}: ask your AI about your D2L Brightspace courses.
|
|
11
|
+
|
|
12
|
+
Usage: amicooked <command>
|
|
13
|
+
|
|
14
|
+
setup Pick your school, sign in, and connect your AI apps
|
|
15
|
+
--school <id|url> e.g. mcmaster, or the URL you log in through
|
|
16
|
+
--clients <list> desktop,code,chatgpt
|
|
17
|
+
--yes accept the detected apps without asking
|
|
18
|
+
login Sign in to your school again
|
|
19
|
+
pair Get a new code for connecting ChatGPT
|
|
20
|
+
status Show what's set up (--json for machines)
|
|
21
|
+
uninstall Disconnect your AI apps (--purge also deletes your login and settings)
|
|
22
|
+
mcp Run the MCP server over stdio (AI apps run this for you)
|
|
23
|
+
serve Run the ChatGPT server (the background service runs this for you)
|
|
24
|
+
`;
|
|
25
|
+
async function runMcp() {
|
|
26
|
+
// stdout carries the protocol; a library logging there would corrupt it
|
|
27
|
+
console.log = console.error;
|
|
28
|
+
const server = createServer({ instructions: serverInstructions() });
|
|
29
|
+
await server.connect(new StdioServerTransport());
|
|
30
|
+
// Keep running until the AI app closes stdin
|
|
31
|
+
return new Promise(() => { });
|
|
32
|
+
}
|
|
33
|
+
async function main(argv) {
|
|
34
|
+
const { values, positionals } = parseArgs({
|
|
35
|
+
args: argv,
|
|
36
|
+
allowPositionals: true,
|
|
37
|
+
options: {
|
|
38
|
+
school: { type: "string" },
|
|
39
|
+
clients: { type: "string" },
|
|
40
|
+
yes: { type: "boolean", short: "y" },
|
|
41
|
+
"no-login": { type: "boolean" },
|
|
42
|
+
json: { type: "boolean" },
|
|
43
|
+
purge: { type: "boolean" },
|
|
44
|
+
quick: { type: "boolean" },
|
|
45
|
+
local: { type: "boolean" },
|
|
46
|
+
port: { type: "string" },
|
|
47
|
+
help: { type: "boolean", short: "h" },
|
|
48
|
+
version: { type: "boolean", short: "v" },
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
if (values.version)
|
|
52
|
+
return console.log(VERSION), 0;
|
|
53
|
+
const command = positionals[0] ?? (process.stdin.isTTY ? "help" : "mcp");
|
|
54
|
+
if (values.help || command === "help")
|
|
55
|
+
return console.log(HELP), 0;
|
|
56
|
+
switch (command) {
|
|
57
|
+
case "mcp":
|
|
58
|
+
return runMcp();
|
|
59
|
+
case "setup":
|
|
60
|
+
return setup({ school: values.school, clients: values.clients, yes: values.yes, login: !values["no-login"] });
|
|
61
|
+
case "login":
|
|
62
|
+
return loginCommand();
|
|
63
|
+
case "pair":
|
|
64
|
+
return pairCommand();
|
|
65
|
+
case "serve":
|
|
66
|
+
// --quick (a throwaway trycloudflare URL) and --local are for development
|
|
67
|
+
return serveCommand({ quick: values.quick, local: values.local, port: values.port ? Number(values.port) : undefined });
|
|
68
|
+
case "status":
|
|
69
|
+
return statusCommand(Boolean(values.json));
|
|
70
|
+
case "uninstall":
|
|
71
|
+
return uninstallCommand(Boolean(values.purge));
|
|
72
|
+
default:
|
|
73
|
+
console.error(`Unknown command: ${command}\n\n${HELP}`);
|
|
74
|
+
return 1;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
|
|
78
|
+
console.error(error instanceof Error ? error.message : error);
|
|
79
|
+
process.exit(1);
|
|
80
|
+
});
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { clearTokenCache, getToken } from "./auth.js";
|
|
2
|
+
import { getSchool } from "./config.js";
|
|
3
|
+
import { API_VERSIONS } from "./schools.js";
|
|
4
|
+
const LE = API_VERSIONS.le;
|
|
5
|
+
const LP = API_VERSIONS.lp;
|
|
6
|
+
const MAX_CONCURRENT = 4;
|
|
7
|
+
const REQUEST_TIMEOUT_MS = 20000;
|
|
8
|
+
export class D2LApiError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
constructor(status, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.name = "D2LApiError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Caps how many D2L requests run at once, so fanning out over every course stays polite. */
|
|
17
|
+
class Limiter {
|
|
18
|
+
max;
|
|
19
|
+
active = 0;
|
|
20
|
+
queue = [];
|
|
21
|
+
constructor(max) {
|
|
22
|
+
this.max = max;
|
|
23
|
+
}
|
|
24
|
+
async run(fn) {
|
|
25
|
+
if (this.active >= this.max)
|
|
26
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
27
|
+
this.active++;
|
|
28
|
+
try {
|
|
29
|
+
return await fn();
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
this.active--;
|
|
33
|
+
this.queue.shift()?.();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export class D2LClient {
|
|
38
|
+
limiter = new Limiter(MAX_CONCURRENT);
|
|
39
|
+
async request(method, path) {
|
|
40
|
+
const url = `https://${getSchool().host}${path}`;
|
|
41
|
+
return this.limiter.run(async () => {
|
|
42
|
+
let response;
|
|
43
|
+
// A 401 means the token was rejected (e.g. expired or revoked early):
|
|
44
|
+
// drop it, log in again, and retry once
|
|
45
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
46
|
+
const token = await getToken();
|
|
47
|
+
response = await fetch(url, {
|
|
48
|
+
method,
|
|
49
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
50
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
51
|
+
});
|
|
52
|
+
if (response.status !== 401 || attempt === 2)
|
|
53
|
+
break;
|
|
54
|
+
clearTokenCache();
|
|
55
|
+
}
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
const text = (await response.text()).slice(0, 300);
|
|
58
|
+
// Expected misses (a final grade that isn't released yet) are normal, so this only logs when asked
|
|
59
|
+
if (process.env.AMICOOKED_DEBUG)
|
|
60
|
+
console.error(`[api] ${method} ${path} -> ${response.status}`);
|
|
61
|
+
throw new D2LApiError(response.status, `D2L API error ${response.status}: ${text}`);
|
|
62
|
+
}
|
|
63
|
+
return (await response.json());
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
get(path) {
|
|
67
|
+
return this.request("GET", path);
|
|
68
|
+
}
|
|
69
|
+
// Dropbox/Assignment endpoints
|
|
70
|
+
getDropboxFolders(orgUnitId) {
|
|
71
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/dropbox/folders/`);
|
|
72
|
+
}
|
|
73
|
+
getDropboxFolder(orgUnitId, folderId) {
|
|
74
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/dropbox/folders/${folderId}`);
|
|
75
|
+
}
|
|
76
|
+
getDropboxSubmissions(orgUnitId, folderId) {
|
|
77
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/dropbox/folders/${folderId}/submissions/`);
|
|
78
|
+
}
|
|
79
|
+
// Content endpoints
|
|
80
|
+
getContentToc(orgUnitId) {
|
|
81
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/content/toc`);
|
|
82
|
+
}
|
|
83
|
+
getContentTopic(orgUnitId, topicId) {
|
|
84
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/content/topics/${topicId}`);
|
|
85
|
+
}
|
|
86
|
+
getContentModules(orgUnitId) {
|
|
87
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/content/root/`);
|
|
88
|
+
}
|
|
89
|
+
getContentModule(orgUnitId, moduleId) {
|
|
90
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/content/modules/${moduleId}/structure/`);
|
|
91
|
+
}
|
|
92
|
+
// User and course info
|
|
93
|
+
whoami() {
|
|
94
|
+
return this.get(`/d2l/api/lp/${LP}/users/whoami`);
|
|
95
|
+
}
|
|
96
|
+
getCourse(orgUnitId) {
|
|
97
|
+
return this.get(`/d2l/api/lp/${LP}/courses/${orgUnitId}`);
|
|
98
|
+
}
|
|
99
|
+
// Grades endpoints
|
|
100
|
+
getMyGradeValues(orgUnitId) {
|
|
101
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/grades/values/myGradeValues/`);
|
|
102
|
+
}
|
|
103
|
+
/** The course's final calculated grade; 403/404 until the instructor releases it. */
|
|
104
|
+
getMyFinalGrade(orgUnitId) {
|
|
105
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/grades/final/values/myGradeValue`);
|
|
106
|
+
}
|
|
107
|
+
// Calendar endpoints
|
|
108
|
+
getMyCalendarEvents(orgUnitId, startDateTime, endDateTime) {
|
|
109
|
+
const params = new URLSearchParams({ startDateTime, endDateTime });
|
|
110
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/calendar/events/myEvents/?${params}`);
|
|
111
|
+
}
|
|
112
|
+
// News/Announcements endpoints
|
|
113
|
+
getNews(orgUnitId) {
|
|
114
|
+
return this.get(`/d2l/api/le/${LE}/${orgUnitId}/news/`);
|
|
115
|
+
}
|
|
116
|
+
// Results are paged (100 per page); follow the bookmark to get all of them
|
|
117
|
+
async getMyEnrollments() {
|
|
118
|
+
const items = [];
|
|
119
|
+
let bookmark = "";
|
|
120
|
+
do {
|
|
121
|
+
const query = bookmark ? `?bookmark=${encodeURIComponent(bookmark)}` : "";
|
|
122
|
+
const page = (await this.get(`/d2l/api/lp/${LP}/enrollments/myenrollments/${query}`));
|
|
123
|
+
items.push(...page.Items);
|
|
124
|
+
bookmark = page.PagingInfo?.HasMoreItems ? page.PagingInfo.Bookmark : "";
|
|
125
|
+
} while (bookmark);
|
|
126
|
+
return { Items: items };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export const client = new D2LClient();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { OAuthStore } from "../remote/oauth.js";
|
|
2
|
+
import { installService, serviceInstalled, uninstallService } from "../remote/service.js";
|
|
3
|
+
import { ensureCloudflared, ensureTunnel, readTunnel } from "../remote/tunnel.js";
|
|
4
|
+
import { selfCommand } from "./self.js";
|
|
5
|
+
/** Give this computer a permanent ChatGPT URL and keep `amicooked serve` running in the background. */
|
|
6
|
+
export async function installChatGPT() {
|
|
7
|
+
const tunnel = await ensureTunnel();
|
|
8
|
+
await ensureCloudflared();
|
|
9
|
+
installService(selfCommand(["serve"]));
|
|
10
|
+
return { url: `${tunnel.url}/mcp`, pairingCode: new OAuthStore().newPairingCode() };
|
|
11
|
+
}
|
|
12
|
+
export function chatgptUrl() {
|
|
13
|
+
const tunnel = readTunnel();
|
|
14
|
+
return tunnel && serviceInstalled() ? `${tunnel.url}/mcp` : null;
|
|
15
|
+
}
|
|
16
|
+
export function chatgptSteps(url, pairingCode) {
|
|
17
|
+
return [
|
|
18
|
+
"In ChatGPT (on the web):",
|
|
19
|
+
" 1. Settings → Apps & Connectors → Advanced settings → turn on Developer mode",
|
|
20
|
+
" 2. Apps & Connectors → Create",
|
|
21
|
+
` 3. Name: Am I Cooked · URL: ${url} · Authentication: OAuth`,
|
|
22
|
+
` 4. When ChatGPT asks for a code, enter ${pairingCode} (valid 10 minutes; \`amicooked pair\` makes a new one)`,
|
|
23
|
+
"ChatGPT can reach Am I Cooked while this computer is on and awake.",
|
|
24
|
+
].join("\n");
|
|
25
|
+
}
|
|
26
|
+
/** Stop the background service and disconnect every ChatGPT session. The tunnel is kept for next time. */
|
|
27
|
+
export function uninstallChatGPT() {
|
|
28
|
+
new OAuthStore().revokeAll();
|
|
29
|
+
return uninstallService();
|
|
30
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
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 runClaude = (args) => spawnSync("claude", args, { encoding: "utf8", shell: process.platform === "win32", timeout: 30000 });
|
|
8
|
+
export function hasClaudeCode(run = runClaude) {
|
|
9
|
+
const result = run(["--version"]);
|
|
10
|
+
return !result.error && result.status === 0;
|
|
11
|
+
}
|
|
12
|
+
/** `claude mcp add` at user scope, so Am I Cooked works in every project. Re-adding replaces the old entry. */
|
|
13
|
+
export function installClaudeCode(launch, run = runClaude) {
|
|
14
|
+
run(["mcp", "remove", SERVER_NAME, "-s", "user"]);
|
|
15
|
+
const env = Object.entries(launch.env ?? {}).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
|
|
16
|
+
const result = run(["mcp", "add", SERVER_NAME, "-s", "user", ...env, "--", launch.command, ...launch.args]);
|
|
17
|
+
if (result.error || result.status !== 0) {
|
|
18
|
+
throw new Error(`\`claude mcp add\` failed: ${(result.stderr || result.error?.message || "").trim()}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function uninstallClaudeCode(run = runClaude) {
|
|
22
|
+
run(["mcp", "remove", SERVER_NAME, "-s", "user"]);
|
|
23
|
+
}
|
|
24
|
+
export function skillPath(home = os.homedir()) {
|
|
25
|
+
return path.join(home, ".claude", "skills", SERVER_NAME, "SKILL.md");
|
|
26
|
+
}
|
|
27
|
+
/** Install the skill that teaches Claude Code how to use the tools. */
|
|
28
|
+
export function installSkill(home = os.homedir()) {
|
|
29
|
+
const file = skillPath(home);
|
|
30
|
+
if (fs.existsSync(file) && fs.readFileSync(file, "utf8") === SKILL_MD)
|
|
31
|
+
return "unchanged";
|
|
32
|
+
const existed = fs.existsSync(file);
|
|
33
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
34
|
+
fs.writeFileSync(file, SKILL_MD);
|
|
35
|
+
return existed ? "updated" : "added";
|
|
36
|
+
}
|
|
37
|
+
export function uninstallSkill(home = os.homedir()) {
|
|
38
|
+
const dir = path.dirname(skillPath(home));
|
|
39
|
+
if (!fs.existsSync(dir))
|
|
40
|
+
return "absent";
|
|
41
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
42
|
+
return "removed";
|
|
43
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "child_process";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
export const SERVER_NAME = "amicooked";
|
|
6
|
+
const currentEnv = () => ({
|
|
7
|
+
platform: process.platform,
|
|
8
|
+
home: os.homedir(),
|
|
9
|
+
appData: process.env.APPDATA,
|
|
10
|
+
localAppData: process.env.LOCALAPPDATA,
|
|
11
|
+
});
|
|
12
|
+
/** Where Claude Desktop keeps its config folder, if it's installed. */
|
|
13
|
+
export function claudeDesktopDir(env = currentEnv()) {
|
|
14
|
+
const candidates = [];
|
|
15
|
+
if (env.platform === "darwin")
|
|
16
|
+
candidates.push(path.join(env.home, "Library", "Application Support", "Claude"));
|
|
17
|
+
if (env.platform === "win32") {
|
|
18
|
+
if (env.appData)
|
|
19
|
+
candidates.push(path.join(env.appData, "Claude"));
|
|
20
|
+
// The Microsoft Store build keeps its data inside the package folder
|
|
21
|
+
const packages = env.localAppData && path.join(env.localAppData, "Packages");
|
|
22
|
+
if (packages && fs.existsSync(packages)) {
|
|
23
|
+
for (const dir of fs.readdirSync(packages).filter((d) => d.startsWith("Claude_"))) {
|
|
24
|
+
candidates.push(path.join(packages, dir, "LocalCache", "Roaming", "Claude"));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (env.platform === "linux")
|
|
29
|
+
candidates.push(path.join(env.home, ".config", "Claude"));
|
|
30
|
+
return candidates.find((dir) => fs.existsSync(dir)) ?? null;
|
|
31
|
+
}
|
|
32
|
+
export class InvalidConfigError extends Error {
|
|
33
|
+
}
|
|
34
|
+
function readConfig(file) {
|
|
35
|
+
if (!fs.existsSync(file))
|
|
36
|
+
return {};
|
|
37
|
+
const text = fs.readFileSync(file, "utf8");
|
|
38
|
+
if (!text.trim())
|
|
39
|
+
return {};
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(text);
|
|
42
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
43
|
+
return parsed;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// fall through
|
|
47
|
+
}
|
|
48
|
+
throw new InvalidConfigError(`${file} isn't valid JSON, so it was left alone.`);
|
|
49
|
+
}
|
|
50
|
+
function writeConfig(file, config) {
|
|
51
|
+
// One backup of the student's original config, the first time we touch it
|
|
52
|
+
const backup = `${file}.amicooked.bak`;
|
|
53
|
+
if (fs.existsSync(file) && !fs.existsSync(backup))
|
|
54
|
+
fs.copyFileSync(file, backup);
|
|
55
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
56
|
+
fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n");
|
|
57
|
+
fs.renameSync(tmp, file);
|
|
58
|
+
}
|
|
59
|
+
/** Add or update our entry in claude_desktop_config.json, keeping everything else as it was. */
|
|
60
|
+
export function installClaudeDesktop(dir, launch) {
|
|
61
|
+
const file = path.join(dir, "claude_desktop_config.json");
|
|
62
|
+
const config = readConfig(file);
|
|
63
|
+
const entry = { command: launch.command, args: launch.args, ...(launch.env ? { env: launch.env } : {}) };
|
|
64
|
+
const existing = config.mcpServers?.[SERVER_NAME];
|
|
65
|
+
if (JSON.stringify(existing) === JSON.stringify(entry))
|
|
66
|
+
return "unchanged";
|
|
67
|
+
config.mcpServers = { ...(config.mcpServers ?? {}), [SERVER_NAME]: entry };
|
|
68
|
+
writeConfig(file, config);
|
|
69
|
+
return existing ? "updated" : "added";
|
|
70
|
+
}
|
|
71
|
+
export function uninstallClaudeDesktop(dir) {
|
|
72
|
+
const file = path.join(dir, "claude_desktop_config.json");
|
|
73
|
+
const config = readConfig(file);
|
|
74
|
+
if (!config.mcpServers?.[SERVER_NAME])
|
|
75
|
+
return "absent";
|
|
76
|
+
delete config.mcpServers[SERVER_NAME];
|
|
77
|
+
writeConfig(file, config);
|
|
78
|
+
return "removed";
|
|
79
|
+
}
|
|
80
|
+
/** The JSON a student can paste by hand when we can't edit the file. */
|
|
81
|
+
export function manualSnippet(launch) {
|
|
82
|
+
const entry = { command: launch.command, args: launch.args, ...(launch.env ? { env: launch.env } : {}) };
|
|
83
|
+
return JSON.stringify({ mcpServers: { [SERVER_NAME]: entry } }, null, 2);
|
|
84
|
+
}
|
|
85
|
+
const probe = (command, args) => {
|
|
86
|
+
const r = spawnSync(command, args, { encoding: "utf8", timeout: 10000 });
|
|
87
|
+
return { status: r.error ? null : r.status, stdout: r.stdout ?? "" };
|
|
88
|
+
};
|
|
89
|
+
export function isClaudeDesktopRunning(platform = process.platform, run = probe) {
|
|
90
|
+
// ps, not pgrep: pgrep skips its own ancestors, so it misses the app when setup runs from inside it
|
|
91
|
+
if (platform === "darwin")
|
|
92
|
+
return /\/Claude\.app\/Contents\/MacOS\/Claude$/m.test(run("ps", ["-axo", "comm="]).stdout);
|
|
93
|
+
if (platform === "win32")
|
|
94
|
+
return /claude\.exe/i.test(run("tasklist", ["/FI", "IMAGENAME eq Claude.exe", "/NH"]).stdout);
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
/** Asks the app to quit (never forces it) and waits until it's gone. False if it's still open. */
|
|
98
|
+
export async function quitClaudeDesktop(platform = process.platform, run = probe, waitMs = 15000) {
|
|
99
|
+
if (platform === "darwin")
|
|
100
|
+
run("osascript", ["-e", 'tell application "Claude" to quit']);
|
|
101
|
+
else if (platform === "win32")
|
|
102
|
+
run("taskkill", ["/IM", "Claude.exe"]);
|
|
103
|
+
else
|
|
104
|
+
return false;
|
|
105
|
+
for (const end = Date.now() + waitMs; Date.now() < end;) {
|
|
106
|
+
if (!isClaudeDesktopRunning(platform, run))
|
|
107
|
+
return true;
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
109
|
+
}
|
|
110
|
+
return !isClaudeDesktopRunning(platform, run);
|
|
111
|
+
}
|
|
112
|
+
/** Opens the app again. Only macOS has a reliable way to find it; elsewhere the student opens it. */
|
|
113
|
+
export function openClaudeDesktop(platform = process.platform) {
|
|
114
|
+
if (platform !== "darwin")
|
|
115
|
+
return false;
|
|
116
|
+
spawn("open", ["-a", "Claude"], { stdio: "ignore", detached: true }).unref();
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
@@ -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
|
+
}
|