amicooked 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,231 @@
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 { hasCodex, installCodex, installCodexSkill } from "../clients/codex.js";
8
+ import { selfCommand } from "../clients/self.js";
9
+ import { client } from "../client.js";
10
+ import { getConfig, writeConfig } from "../config.js";
11
+ import { listCourses } from "../courseResolver.js";
12
+ import { detectSchool, findPreset, PRESETS } from "../schools.js";
13
+ import { amICooked } from "../tools/cooked.js";
14
+ const PUBLIC_IDS = ["desktop", "code", "chatgpt-desktop"];
15
+ const CLIENT_IDS = [...PUBLIC_IDS, "chatgpt"];
16
+ const ALIASES = { codex: "chatgpt-desktop", "chatgpt-app": "chatgpt-desktop", "chatgpt-web": "chatgpt" };
17
+ /** Exit code for "the agent needs to ask the student something first". */
18
+ export const NEEDS_INPUT = 2;
19
+ class SetupStop extends Error {
20
+ code;
21
+ constructor(message, code = 1) {
22
+ super(message);
23
+ this.code = code;
24
+ }
25
+ }
26
+ const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
27
+ function presetList() {
28
+ return PRESETS.map((s) => ` ${s.id.padEnd(11)} ${s.name} (${s.lmsName})`).join("\n");
29
+ }
30
+ async function chooseSchool(flag) {
31
+ if (flag)
32
+ return findPreset(flag) ?? (await detectSchool(flag));
33
+ const current = getConfig().school;
34
+ if (!interactive()) {
35
+ if (current)
36
+ return current;
37
+ 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);
38
+ }
39
+ const choice = await p.select({
40
+ message: "Which school do you go to?",
41
+ initialValue: current?.id === "custom" ? "other" : current?.id,
42
+ options: [
43
+ ...PRESETS.map((s) => ({ value: s.id, label: s.name, hint: s.lmsName })),
44
+ { value: "other", label: "Somewhere else", hint: "paste the URL you log in through" },
45
+ ],
46
+ });
47
+ if (p.isCancel(choice))
48
+ throw new SetupStop("Setup cancelled.");
49
+ if (choice !== "other")
50
+ return findPreset(choice);
51
+ const url = await p.text({
52
+ message: "Paste the web address you use to log in to your courses",
53
+ placeholder: "https://learn.myschool.edu",
54
+ validate: (v) => (v?.trim() ? undefined : "Paste a URL"),
55
+ });
56
+ if (p.isCancel(url))
57
+ throw new SetupStop("Setup cancelled.");
58
+ const spin = p.spinner();
59
+ spin.start("Finding your school's Brightspace");
60
+ try {
61
+ const school = await detectSchool(url);
62
+ spin.stop(`Found ${school.host}`);
63
+ return school;
64
+ }
65
+ catch (error) {
66
+ spin.stop("Couldn't find it");
67
+ throw error;
68
+ }
69
+ }
70
+ async function chooseClients(flag, detected, yes) {
71
+ if (flag) {
72
+ const ids = flag.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean).map((id) => ALIASES[id] ?? id);
73
+ const unknown = ids.filter((id) => !CLIENT_IDS.includes(id));
74
+ if (unknown.length)
75
+ throw new SetupStop(`Unknown app: ${unknown.join(", ")}. Use ${PUBLIC_IDS.join(", ")}.`);
76
+ return [...new Set(ids)];
77
+ }
78
+ const defaults = PUBLIC_IDS.filter((id) => detected[id]);
79
+ if (yes || !interactive())
80
+ return defaults;
81
+ const chosen = await p.multiselect({
82
+ message: "Where do you want to use it?",
83
+ initialValues: defaults,
84
+ required: false,
85
+ options: [
86
+ { value: "desktop", label: "Claude Desktop", hint: detected.desktop ? "found" : "not found" },
87
+ { value: "code", label: "Claude Code", hint: detected.code ? "found" : "not found" },
88
+ { value: "chatgpt-desktop", label: "ChatGPT desktop app", hint: detected["chatgpt-desktop"] ? "found" : "not found" },
89
+ ],
90
+ });
91
+ if (p.isCancel(chosen))
92
+ throw new SetupStop("Setup cancelled.");
93
+ return chosen;
94
+ }
95
+ /** Claude Desktop saves its own config over ours when it quits, so it has to be closed before we write. */
96
+ async function closeClaudeDesktop() {
97
+ if (!isClaudeDesktopRunning())
98
+ return "not_running";
99
+ // An agent may be running this from inside Claude Desktop; never close it without asking
100
+ if (!interactive())
101
+ return "left_open";
102
+ 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." });
103
+ if (p.isCancel(ok) || !ok)
104
+ return "left_open";
105
+ return (await quitClaudeDesktop()) ? "closed" : "left_open";
106
+ }
107
+ async function configureClients(clients) {
108
+ const done = [];
109
+ const launch = selfCommand(["mcp"]);
110
+ if (clients.includes("desktop")) {
111
+ const dir = claudeDesktopDir();
112
+ if (!dir) {
113
+ p.log.warn("Claude Desktop isn't installed. Get it at https://claude.ai/download, then run `amicooked setup` again.");
114
+ }
115
+ else {
116
+ try {
117
+ const state = await closeClaudeDesktop();
118
+ const result = installClaudeDesktop(dir, launch);
119
+ if (state === "left_open" && result !== "unchanged") {
120
+ // Written, but the open app will save its own copy over it when it quits
121
+ p.log.warn("Claude Desktop is open, so it will undo this when it quits. Quit it, then run `amicooked setup --clients desktop`.");
122
+ }
123
+ else {
124
+ p.log.success(`Claude Desktop: ${result === "unchanged" ? "already set up" : "set up"}`);
125
+ done.push(state === "closed" && openClaudeDesktop() ? "desktop-reopened" : "desktop");
126
+ }
127
+ }
128
+ catch (error) {
129
+ if (!(error instanceof InvalidConfigError))
130
+ throw error;
131
+ p.log.warn(`${error.message}\nAdd this to it yourself:\n${manualSnippet(launch)}`);
132
+ }
133
+ }
134
+ }
135
+ if (clients.includes("code")) {
136
+ if (!hasClaudeCode()) {
137
+ p.log.warn("Claude Code isn't installed, so it was skipped.");
138
+ }
139
+ else {
140
+ installClaudeCode(launch);
141
+ installSkill();
142
+ p.log.success("Claude Code: set up, with the amicooked skill");
143
+ done.push("code");
144
+ }
145
+ }
146
+ if (clients.includes("chatgpt-desktop")) {
147
+ if (!hasCodex()) {
148
+ p.log.warn("The ChatGPT desktop app isn't installed. Get it at https://chatgpt.com/download, then run `amicooked setup` again.");
149
+ }
150
+ else {
151
+ // Runs on this computer like Claude Desktop does; no tunnel or domain involved
152
+ const result = installCodex(launch);
153
+ installCodexSkill();
154
+ p.log.success(`ChatGPT desktop app: ${result === "unchanged" ? "already set up" : "set up"}, with the amicooked skill`);
155
+ done.push("chatgpt-desktop");
156
+ }
157
+ }
158
+ if (clients.includes("chatgpt") && !process.env.AMICOOKED_TUNNEL_API) {
159
+ p.log.warn("ChatGPT on the web isn't available yet. For the ChatGPT desktop app, use `--clients chatgpt-desktop`.");
160
+ }
161
+ else if (clients.includes("chatgpt")) {
162
+ const spin = p.spinner();
163
+ spin.start("Setting up your private ChatGPT connection");
164
+ try {
165
+ const { url, pairingCode } = await installChatGPT();
166
+ spin.stop("ChatGPT: running in the background");
167
+ p.note(chatgptSteps(url, pairingCode), "Connect ChatGPT");
168
+ done.push("chatgpt");
169
+ }
170
+ catch (error) {
171
+ spin.stop(`ChatGPT: ${error instanceof Error ? error.message : error}`);
172
+ }
173
+ }
174
+ return done;
175
+ }
176
+ async function firstRoast() {
177
+ const spin = p.spinner();
178
+ spin.start("Checking whether you're cooked");
179
+ try {
180
+ const report = await amICooked({});
181
+ const { heat, heatLabel, dueSoon, overdue } = report.summary;
182
+ spin.stop(`Heat: ${heatLabel} (${heat}/10) · ${dueSoon} due this week${overdue ? ` · ${overdue} overdue` : ""}`);
183
+ }
184
+ catch (error) {
185
+ spin.stop(`Couldn't build your first report: ${error instanceof Error ? error.message : error}`);
186
+ }
187
+ }
188
+ export async function setup(options) {
189
+ p.intro("Am I Cooked");
190
+ try {
191
+ const school = await chooseSchool(options.school);
192
+ p.log.info(`School: ${school.name} (${school.host})`);
193
+ const browser = getConfig().browser ?? (await detectChannel());
194
+ if (!browser) {
195
+ throw new SetupStop("Am I Cooked logs in through Google Chrome or Microsoft Edge. Install one of them, then run setup again.");
196
+ }
197
+ const schoolChanged = getConfig().school?.host !== school.host;
198
+ writeConfig({ school, browser });
199
+ if (options.login !== false && (schoolChanged || !hasActiveSession())) {
200
+ p.log.step("A browser window is opening. Sign in to your school there; this window waits for you.");
201
+ await login();
202
+ }
203
+ if (options.login !== false) {
204
+ const me = (await client.whoami());
205
+ const courses = await listCourses();
206
+ p.log.success(`Signed in${me.FirstName ? ` as ${me.FirstName}` : ""}. Found ${courses.length} course${courses.length === 1 ? "" : "s"}.`);
207
+ }
208
+ const detected = { desktop: Boolean(claudeDesktopDir()), code: hasClaudeCode(), "chatgpt-desktop": hasCodex(), chatgpt: false };
209
+ const done = await configureClients(await chooseClients(options.clients, detected, Boolean(options.yes)));
210
+ if (options.login !== false)
211
+ await firstRoast();
212
+ const next = done.includes("desktop-reopened")
213
+ ? "Claude Desktop is reopening. Ask it: am I cooked?"
214
+ : done.includes("desktop")
215
+ ? "Open Claude Desktop and ask: am I cooked?"
216
+ : done.includes("chatgpt-desktop")
217
+ ? "Restart the ChatGPT desktop app, then ask: am I cooked?"
218
+ : done.includes("code")
219
+ ? "Start Claude Code and ask: am I cooked?"
220
+ : done.includes("chatgpt")
221
+ ? "Finish connecting in ChatGPT, then ask: am I cooked?"
222
+ : "Nothing was set up. Run `amicooked setup` again and pick an app.";
223
+ p.outro(next);
224
+ return 0;
225
+ }
226
+ catch (error) {
227
+ const code = error instanceof SetupStop ? error.code : 1;
228
+ p.cancel(error instanceof Error ? error.message : String(error));
229
+ return code;
230
+ }
231
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,78 @@
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-desktop
17
+ --yes accept the detected apps without asking
18
+ login Sign in to your school again
19
+ status Show what's set up (--json for machines)
20
+ uninstall Disconnect your AI apps (--purge also deletes your login and settings)
21
+ mcp Run the MCP server over stdio (AI apps run this for you)
22
+ `;
23
+ async function runMcp() {
24
+ // stdout carries the protocol; a library logging there would corrupt it
25
+ console.log = console.error;
26
+ const server = createServer({ instructions: serverInstructions() });
27
+ await server.connect(new StdioServerTransport());
28
+ // Keep running until the AI app closes stdin
29
+ return new Promise(() => { });
30
+ }
31
+ async function main(argv) {
32
+ const { values, positionals } = parseArgs({
33
+ args: argv,
34
+ allowPositionals: true,
35
+ options: {
36
+ school: { type: "string" },
37
+ clients: { type: "string" },
38
+ yes: { type: "boolean", short: "y" },
39
+ "no-login": { type: "boolean" },
40
+ json: { type: "boolean" },
41
+ purge: { type: "boolean" },
42
+ quick: { type: "boolean" },
43
+ local: { type: "boolean" },
44
+ port: { type: "string" },
45
+ help: { type: "boolean", short: "h" },
46
+ version: { type: "boolean", short: "v" },
47
+ },
48
+ });
49
+ if (values.version)
50
+ return console.log(VERSION), 0;
51
+ const command = positionals[0] ?? (process.stdin.isTTY ? "help" : "mcp");
52
+ if (values.help || command === "help")
53
+ return console.log(HELP), 0;
54
+ switch (command) {
55
+ case "mcp":
56
+ return runMcp();
57
+ case "setup":
58
+ return setup({ school: values.school, clients: values.clients, yes: values.yes, login: !values["no-login"] });
59
+ case "login":
60
+ return loginCommand();
61
+ case "pair":
62
+ return pairCommand();
63
+ case "serve":
64
+ // --quick (a throwaway trycloudflare URL) and --local are for development
65
+ return serveCommand({ quick: values.quick, local: values.local, port: values.port ? Number(values.port) : undefined });
66
+ case "status":
67
+ return statusCommand(Boolean(values.json));
68
+ case "uninstall":
69
+ return uninstallCommand(Boolean(values.purge));
70
+ default:
71
+ console.error(`Unknown command: ${command}\n\n${HELP}`);
72
+ return 1;
73
+ }
74
+ }
75
+ main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
76
+ console.error(error instanceof Error ? error.message : error);
77
+ process.exit(1);
78
+ });
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
+ }