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 ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Uday Singh Kanwar
4
+ Copyright (c) 2026 Hamza Ammar
5
+ Copyright (c) 2025 Bence Redmond
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # Am I Cooked
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ask your AI if you're cooked. Am I Cooked connects Claude and ChatGPT to your D2L Brightspace courses (Avenue to Learn, LEARN, onQ, OWL Brightspace, CourseLink and others) so they can read your grades, deadlines, announcements and course files, and tell you straight.
4
+
5
+ It runs on your own computer. You sign in to your school in a normal browser window; your password never touches anything else.
6
+
7
+ ## Install
8
+
9
+ macOS / Linux:
10
+
11
+ ```sh
12
+ curl -fsSL https://amicooked-mcp.vercel.app/install.sh | sh
13
+ ```
14
+
15
+ Windows (PowerShell):
16
+
17
+ ```powershell
18
+ irm https://amicooked-mcp.vercel.app/install.ps1 | iex
19
+ ```
20
+
21
+ With Node.js 22+: `npx -y amicooked@0 setup`
22
+
23
+ Setup asks for your school, opens a browser window to sign in, and connects the AI apps you use. Then ask: **am I cooked?**
24
+
25
+ ## What you can ask
26
+
27
+ - "Am I cooked this week?"
28
+ - "What's my grade in 3BB4 so far?"
29
+ - "Did I submit lab 4?"
30
+ - "Summarize the week 7 slides."
31
+ - "Anything new from my profs?"
32
+ - "What's on the midterm?"
33
+
34
+ ## Tools
35
+
36
+ | Tool | What it does |
37
+ |---|---|
38
+ | `am_i_cooked` | Every current course at once: grade so far, what's due, overdue work, new announcements, and a heat score |
39
+ | `get_my_courses` | Your courses |
40
+ | `get_my_grades` | Grade items and feedback for a course |
41
+ | `get_upcoming_due_dates` | Calendar deadlines, for one course or all of them |
42
+ | `get_announcements` | Instructor announcements |
43
+ | `get_assignments` | Assignments with due dates and whether you submitted |
44
+ | `get_course_content` | Modules, lectures and files |
45
+ | `download_file` | Save a course file and read its text (PDF, Word, PowerPoint) |
46
+ | `read_file` | Read a file you already downloaded |
47
+
48
+ Every tool is read-only. Course tools take a code like `"3BB4"`.
49
+
50
+ ## Schools
51
+
52
+ Presets for McMaster, Waterloo, Western, Queen's, Guelph, Laurier, TMU, uOttawa, Carleton, Brock, Windsor, Laurentian and Lakehead. Any other Brightspace school works with the URL you log in through. Login is tested at McMaster; other schools should work and we'd love to hear if they don't.
53
+
54
+ ## ChatGPT
55
+
56
+ `amicooked setup --clients chatgpt` gives your computer a private, permanent HTTPS address and runs Am I Cooked in the background. Add it in ChatGPT under Settings → Apps & Connectors (Developer mode), and enter the pairing code from `amicooked pair`. ChatGPT can reach it while your computer is on and awake. Requests travel through Cloudflare's network to your computer; nothing is stored on our servers.
57
+
58
+ ## Commands
59
+
60
+ ```
61
+ amicooked setup pick your school, sign in, connect apps
62
+ amicooked login sign in again
63
+ amicooked pair new ChatGPT pairing code
64
+ amicooked status what's set up
65
+ amicooked uninstall disconnect apps (--purge deletes your login and settings)
66
+ ```
67
+
68
+ Your settings and login live in `~/.amicooked`; downloaded files go to `~/Downloads/amicooked`.
69
+
70
+ ## Development
71
+
72
+ ```sh
73
+ npm install
74
+ npm test
75
+ npm run build # TypeScript to dist/
76
+ npm run build:bin # standalone binaries in build/ (uses Bun)
77
+ node dist/cli.js setup
78
+ ```
79
+
80
+ `skill/SKILL.md` is the single source for the agent skill; `npm run sync:skill` copies it (and `install/`) into `src/skill.ts` and `site/`.
81
+
82
+ ## Not affiliated
83
+
84
+ Am I Cooked is an independent project. It isn't affiliated with or endorsed by D2L Corporation or any university. Brightspace is a trademark of D2L Corporation. It only reads your own data; check your school's policies before using it.
85
+
86
+ ## Credits
87
+
88
+ Built on work by [Hamza Ammar](https://github.com/hamzakammar) ([mcp-workspace](https://github.com/hamzakammar/mcp-workspace)), [Bence Redmond](https://github.com/General-Mudkip) ([d2l-mcp-server](https://github.com/General-Mudkip/d2l-mcp-server)) and alanxue1. MIT licensed.
package/dist/auth.js ADDED
@@ -0,0 +1,171 @@
1
+ import * as fs from "fs";
2
+ import { canShowWindow, openProfile } from "./browser.js";
3
+ import { getSchool, paths, writePrivateFile } from "./config.js";
4
+ /** Thrown when a login window is open but the student hasn't finished signing in yet. */
5
+ export class LoginPendingError extends Error {
6
+ constructor() {
7
+ super("A login window for your school just opened on your computer. Sign in there, then ask again.");
8
+ this.name = "LoginPendingError";
9
+ }
10
+ }
11
+ // Refresh this long before the token actually expires
12
+ const EXPIRY_MARGIN_MS = 3 * 60 * 1000;
13
+ const SILENT_TIMEOUT_MS = 15000;
14
+ const INTERACTIVE_TIMEOUT_MS = 5 * 60 * 1000;
15
+ /** How long a tool call waits for an interactive login; MCP clients give up around 60s. */
16
+ export const IN_CALL_WAIT_MS = 40000;
17
+ let session = null;
18
+ /**
19
+ * Expiry time of a D2L access token. They're JWTs that live about an hour,
20
+ * so read the real `exp` claim rather than assuming a lifetime.
21
+ */
22
+ export function tokenExpiry(token) {
23
+ try {
24
+ const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString());
25
+ if (typeof payload.exp === "number")
26
+ return payload.exp * 1000;
27
+ }
28
+ catch {
29
+ // Not a JWT; fall through to a conservative default
30
+ }
31
+ return Date.now() + 50 * 60 * 1000;
32
+ }
33
+ function isFresh(s) {
34
+ return !!s && Date.now() < s.expiresAt - EXPIRY_MARGIN_MS;
35
+ }
36
+ /** A token another Am I Cooked process (Claude Desktop, the ChatGPT service) already saved. */
37
+ function readSavedSession() {
38
+ try {
39
+ return JSON.parse(fs.readFileSync(paths().token, "utf8"));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ function saveSession(s) {
46
+ session = s;
47
+ writePrivateFile(paths().token, JSON.stringify(s));
48
+ }
49
+ function isSignedIn(url, school) {
50
+ try {
51
+ const u = new URL(url);
52
+ return u.host === school.host && u.pathname.startsWith("/d2l/") && !u.pathname.startsWith("/d2l/login");
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Watch one login attempt in `tab`, which opened on the school's login page: wait until
60
+ * the browser is signed in to D2L and a page has made an authenticated API call.
61
+ */
62
+ async function captureSession(tab, school, timeoutMs) {
63
+ let token = "";
64
+ tab.onRequest((url, headers) => {
65
+ const auth = headers["Authorization"] ?? headers["authorization"];
66
+ if (url.includes("/d2l/api/") && auth?.startsWith("Bearer "))
67
+ token = auth.slice(7);
68
+ });
69
+ const deadline = Date.now() + timeoutMs;
70
+ let visitedHome = false;
71
+ while (Date.now() < deadline && !tab.isClosed() && !token) {
72
+ const url = await tab.url().catch(() => "");
73
+ if (isSignedIn(url, school) && !visitedHome) {
74
+ // The home page's widgets call the API with a Bearer token we can capture
75
+ visitedHome = true;
76
+ if (!new URL(url).pathname.startsWith("/d2l/home"))
77
+ await tab.goto(`https://${school.host}/d2l/home`).catch(() => { });
78
+ }
79
+ await new Promise((resolve) => setTimeout(resolve, 500));
80
+ }
81
+ if (!token)
82
+ return null;
83
+ return { token, expiresAt: tokenExpiry(token), cookies: await tab.cookieHeader(`https://${school.host}`) };
84
+ }
85
+ const startUrl = (school) => school.loginUrl ?? `https://${school.host}/d2l/home`;
86
+ async function attempt(school, headless, timeoutMs) {
87
+ const profile = await openProfile(headless, startUrl(school));
88
+ try {
89
+ return await captureSession(profile.tab, school, timeoutMs);
90
+ }
91
+ finally {
92
+ await profile.close().catch(() => { });
93
+ }
94
+ }
95
+ /** How logins actually happen; swapped out in tests. */
96
+ export const driver = {
97
+ silent: (school) => attempt(school, true, SILENT_TIMEOUT_MS),
98
+ async interactive(school) {
99
+ if (!canShowWindow()) {
100
+ throw new Error("Logging in needs a desktop session with a display. Run `amicooked login` from your desktop.");
101
+ }
102
+ return attempt(school, false, INTERACTIVE_TIMEOUT_MS);
103
+ },
104
+ };
105
+ let silentInFlight = null;
106
+ let interactiveInFlight = null;
107
+ /** Open the login window, or join the one that's already open. Resolves once signed in. */
108
+ export function login() {
109
+ if (!interactiveInFlight) {
110
+ const school = getSchool();
111
+ interactiveInFlight = driver
112
+ .interactive(school)
113
+ .then((s) => {
114
+ if (!s)
115
+ throw new Error("Login timed out. Run `amicooked login` to try again.");
116
+ saveSession(s);
117
+ return s;
118
+ })
119
+ .finally(() => {
120
+ interactiveInFlight = null;
121
+ });
122
+ }
123
+ return interactiveInFlight;
124
+ }
125
+ /** Log in without showing anything, using the saved browser profile. */
126
+ async function silentLogin() {
127
+ if (!silentInFlight) {
128
+ silentInFlight = driver
129
+ .silent(getSchool())
130
+ .then((s) => {
131
+ if (s)
132
+ saveSession(s);
133
+ return s;
134
+ })
135
+ .finally(() => {
136
+ silentInFlight = null;
137
+ });
138
+ }
139
+ return silentInFlight;
140
+ }
141
+ async function getSession() {
142
+ if (isFresh(session))
143
+ return session;
144
+ const saved = readSavedSession();
145
+ if (isFresh(saved))
146
+ return (session = saved);
147
+ const silent = interactiveInFlight ? null : await silentLogin();
148
+ if (silent)
149
+ return silent;
150
+ // The saved login expired: show the login window and give the student a moment to finish
151
+ const pending = login();
152
+ pending.catch(() => { }); // a later call reports the failure
153
+ const timeout = new Promise((_, reject) => setTimeout(() => reject(new LoginPendingError()), IN_CALL_WAIT_MS).unref());
154
+ return Promise.race([pending, timeout]);
155
+ }
156
+ export async function getToken() {
157
+ return (await getSession()).token;
158
+ }
159
+ /** Cookie header for fetching D2L files directly. */
160
+ export async function getD2LCookies() {
161
+ return (await getSession()).cookies;
162
+ }
163
+ /** Forget the current token, e.g. after D2L rejects it with a 401. */
164
+ export function clearTokenCache() {
165
+ session = null;
166
+ fs.rmSync(paths().token, { force: true });
167
+ }
168
+ /** True if a login is already cached, i.e. D2L requests won't open a browser. */
169
+ export function hasActiveSession() {
170
+ return isFresh(session) || isFresh(readSavedSession());
171
+ }
@@ -0,0 +1,141 @@
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
+ import { CdpConnection } from "./cdp.js";
6
+ import { getConfig, paths } from "./config.js";
7
+ /** Where each browser usually lives, per platform. */
8
+ export function browserCandidates(platform = process.platform, env = process.env, home = os.homedir()) {
9
+ if (platform === "darwin") {
10
+ const app = (dir, name) => path.join(dir, `${name}.app`, "Contents", "MacOS", name);
11
+ return ["/Applications", path.join(home, "Applications")].flatMap((dir) => [
12
+ { channel: "chrome", path: app(dir, "Google Chrome") },
13
+ { channel: "msedge", path: app(dir, "Microsoft Edge") },
14
+ { channel: "chromium", path: app(dir, "Chromium") },
15
+ ]);
16
+ }
17
+ if (platform === "win32") {
18
+ const roots = [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA].filter((r) => Boolean(r));
19
+ return [
20
+ ...roots.map((r) => ({ channel: "chrome", path: path.win32.join(r, "Google", "Chrome", "Application", "chrome.exe") })),
21
+ ...roots.map((r) => ({ channel: "msedge", path: path.win32.join(r, "Microsoft", "Edge", "Application", "msedge.exe") })),
22
+ ];
23
+ }
24
+ const which = (name) => spawnSync("which", [name], { encoding: "utf8" }).stdout?.trim() || "";
25
+ return [
26
+ { channel: "chrome", path: which("google-chrome") || which("google-chrome-stable") },
27
+ { channel: "msedge", path: which("microsoft-edge") || which("microsoft-edge-stable") },
28
+ { channel: "chromium", path: which("chromium") || which("chromium-browser") },
29
+ ].filter((c) => c.path);
30
+ }
31
+ /** The installed browser to log in with: the configured one if present, else Chrome, Edge, then Chromium. */
32
+ export function findBrowser(preferred = getConfig().browser) {
33
+ const found = browserCandidates().filter((c) => fs.existsSync(c.path));
34
+ return found.find((c) => c.channel === preferred) ?? found[0] ?? null;
35
+ }
36
+ export async function detectChannel() {
37
+ return findBrowser(undefined)?.channel ?? null;
38
+ }
39
+ /** True when a visible login window can be shown on this machine. */
40
+ export function canShowWindow() {
41
+ if (process.platform !== "linux")
42
+ return true;
43
+ return Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
44
+ }
45
+ /** Start the browser on our profile and wait for its DevTools address. Exits early if the profile is in use. */
46
+ function launch(executable, headless, startUrl) {
47
+ const args = [
48
+ `--user-data-dir=${paths().browser}`,
49
+ "--remote-debugging-port=0",
50
+ "--no-first-run",
51
+ "--no-default-browser-check",
52
+ "--disable-features=Translate",
53
+ "--window-size=1200,800",
54
+ // Without a desktop keyring, Linux Chrome would prompt to unlock one
55
+ ...(process.platform === "linux" ? ["--password-store=basic"] : []),
56
+ ...(headless ? ["--headless=new"] : []),
57
+ startUrl,
58
+ ];
59
+ fs.mkdirSync(paths().browser, { recursive: true });
60
+ const child = spawn(executable, args, { stdio: ["ignore", "ignore", "pipe"] });
61
+ return new Promise((resolve, reject) => {
62
+ let output = "";
63
+ const timer = setTimeout(() => (child.kill(), reject(new Error("The browser didn't start in time."))), 30000);
64
+ child.stderr.on("data", (d) => {
65
+ output += String(d);
66
+ const match = output.match(/DevTools listening on (ws:\/\/\S+)/);
67
+ if (match)
68
+ clearTimeout(timer), resolve({ child, wsUrl: match[1] });
69
+ });
70
+ child.on("exit", () => {
71
+ clearTimeout(timer);
72
+ reject(new ProfileBusyError());
73
+ });
74
+ });
75
+ }
76
+ class ProfileBusyError extends Error {
77
+ constructor() {
78
+ super("The login browser is already open in another Am I Cooked process.");
79
+ }
80
+ }
81
+ /**
82
+ * Open the persistent profile in ~/.amicooked/browser on `startUrl`, waiting if another
83
+ * Am I Cooked process (e.g. a second AI app) currently has it open.
84
+ */
85
+ export async function openProfile(headless, startUrl) {
86
+ const browser = findBrowser();
87
+ if (!browser)
88
+ throw new Error("Am I Cooked logs in through Google Chrome or Microsoft Edge. Install one, then try again.");
89
+ const deadline = Date.now() + 30000;
90
+ let launched;
91
+ for (;;) {
92
+ try {
93
+ launched = await launch(browser.path, headless, startUrl);
94
+ break;
95
+ }
96
+ catch (error) {
97
+ if (!(error instanceof ProfileBusyError) || Date.now() > deadline)
98
+ throw error;
99
+ await new Promise((resolve) => setTimeout(resolve, 2000));
100
+ }
101
+ }
102
+ const { child, wsUrl } = launched;
103
+ const cdp = await CdpConnection.connect(wsUrl);
104
+ const { targetInfos } = await cdp.send("Target.getTargets");
105
+ const page = targetInfos.find((t) => t.type === "page");
106
+ if (!page)
107
+ throw new Error("The browser opened without a tab.");
108
+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId: page.targetId, flatten: true });
109
+ await cdp.send("Network.enable", {}, sessionId);
110
+ let closed = false;
111
+ cdp.on("Target.detachedFromTarget", (p) => p.sessionId === sessionId && (closed = true));
112
+ child.on("exit", () => (closed = true));
113
+ const tab = {
114
+ url: async () => (await cdp.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, sessionId)).result.value,
115
+ goto: async (url) => {
116
+ await cdp.send("Page.navigate", { url }, sessionId);
117
+ },
118
+ onRequest: (fn) => {
119
+ cdp.on("Network.requestWillBeSent", (p, sid) => sid === sessionId && fn(p.request.url, p.request.headers ?? {}));
120
+ },
121
+ cookieHeader: async (origin) => {
122
+ const { cookies } = await cdp.send("Network.getCookies", { urls: [origin] }, sessionId);
123
+ return cookies.map((c) => `${c.name}=${c.value}`).join("; ");
124
+ },
125
+ isClosed: () => closed || cdp.isClosed,
126
+ };
127
+ return {
128
+ tab,
129
+ close: async () => {
130
+ // A clean Browser.close lets Chrome save cookies to the profile
131
+ await Promise.race([cdp.send("Browser.close").catch(() => { }), new Promise((r) => setTimeout(r, 5000))]);
132
+ cdp.close();
133
+ await new Promise((resolve) => {
134
+ if (child.exitCode !== null)
135
+ return resolve();
136
+ const timer = setTimeout(() => (child.kill(), resolve()), 5000);
137
+ child.once("exit", () => (clearTimeout(timer), resolve()));
138
+ });
139
+ },
140
+ };
141
+ }
package/dist/cdp.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Just enough of the Chrome DevTools Protocol to drive one tab: commands with
3
+ * flattened target sessions, and event listeners. Uses the built-in WebSocket
4
+ * (Node 22+, Bun), so the compiled binary needs nothing on disk.
5
+ */
6
+ export class CdpConnection {
7
+ ws;
8
+ nextId = 1;
9
+ pending = new Map();
10
+ listeners = new Map();
11
+ closed = false;
12
+ constructor(ws) {
13
+ this.ws = ws;
14
+ ws.addEventListener("message", (event) => {
15
+ const msg = JSON.parse(String(event.data));
16
+ if (msg.id !== undefined) {
17
+ const waiter = this.pending.get(msg.id);
18
+ this.pending.delete(msg.id);
19
+ if (msg.error)
20
+ waiter?.reject(new Error(`${msg.error.message} (${msg.error.code})`));
21
+ else
22
+ waiter?.resolve(msg.result);
23
+ }
24
+ else if (msg.method) {
25
+ for (const fn of this.listeners.get(msg.method) ?? [])
26
+ fn(msg.params, msg.sessionId);
27
+ }
28
+ });
29
+ ws.addEventListener("close", () => {
30
+ this.closed = true;
31
+ for (const waiter of this.pending.values())
32
+ waiter.reject(new Error("Browser connection closed"));
33
+ this.pending.clear();
34
+ });
35
+ }
36
+ static connect(url) {
37
+ return new Promise((resolve, reject) => {
38
+ const ws = new WebSocket(url);
39
+ ws.addEventListener("open", () => resolve(new CdpConnection(ws)), { once: true });
40
+ ws.addEventListener("error", () => reject(new Error("Couldn't connect to the browser")), { once: true });
41
+ });
42
+ }
43
+ get isClosed() {
44
+ return this.closed;
45
+ }
46
+ send(method, params = {}, sessionId) {
47
+ if (this.closed)
48
+ return Promise.reject(new Error("Browser connection closed"));
49
+ const id = this.nextId++;
50
+ this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
51
+ return new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
52
+ }
53
+ on(method, fn) {
54
+ if (!this.listeners.has(method))
55
+ this.listeners.set(method, new Set());
56
+ this.listeners.get(method).add(fn);
57
+ return () => this.listeners.get(method)?.delete(fn);
58
+ }
59
+ close() {
60
+ this.ws.close();
61
+ }
62
+ }
@@ -0,0 +1,89 @@
1
+ import * as fs from "fs";
2
+ import { hasActiveSession, login } from "../auth.js";
3
+ import { claudeDesktopDir, SERVER_NAME, uninstallClaudeDesktop } from "../clients/claudeDesktop.js";
4
+ import { hasClaudeCode, skillPath, uninstallClaudeCode, uninstallSkill } from "../clients/claudeCode.js";
5
+ import { chatgptSteps, chatgptUrl, uninstallChatGPT } from "../clients/chatgpt.js";
6
+ import { OAuthStore } from "../remote/oauth.js";
7
+ import { client } from "../client.js";
8
+ import { getConfig, paths } from "../config.js";
9
+ import { VERSION } from "../version.js";
10
+ export async function loginCommand() {
11
+ if (!getConfig().school) {
12
+ console.log("Run `amicooked setup` first to pick your school.");
13
+ return 1;
14
+ }
15
+ console.log("A browser window is opening. Sign in to your school there; this waits for you.");
16
+ await login();
17
+ const me = (await client.whoami());
18
+ console.log(`Signed in${me.FirstName ? ` as ${me.FirstName}` : ""}.`);
19
+ return 0;
20
+ }
21
+ /** A fresh code for ChatGPT's "connect" page. */
22
+ export async function pairCommand() {
23
+ const url = chatgptUrl();
24
+ if (!url) {
25
+ console.log("ChatGPT isn't set up on this computer. Run `amicooked setup --clients chatgpt`.");
26
+ return 1;
27
+ }
28
+ console.log(chatgptSteps(url, new OAuthStore().newPairingCode()));
29
+ return 0;
30
+ }
31
+ function desktopConfigured() {
32
+ const dir = claudeDesktopDir();
33
+ if (!dir)
34
+ return false;
35
+ try {
36
+ const config = JSON.parse(fs.readFileSync(`${dir}/claude_desktop_config.json`, "utf8"));
37
+ return Boolean(config.mcpServers?.[SERVER_NAME]);
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ export async function statusCommand(json) {
44
+ const config = getConfig();
45
+ const status = {
46
+ version: VERSION,
47
+ school: config.school ? `${config.school.name} (${config.school.host})` : null,
48
+ browser: config.browser ?? null,
49
+ signedIn: hasActiveSession(),
50
+ claudeDesktop: claudeDesktopDir() ? (desktopConfigured() ? "set up" : "installed, not set up") : "not installed",
51
+ claudeCode: hasClaudeCode() ? (fs.existsSync(skillPath()) ? "set up" : "installed") : "not installed",
52
+ chatgpt: chatgptUrl() ?? "not set up",
53
+ dataFolder: paths().home,
54
+ filesFolder: config.filesDir,
55
+ };
56
+ if (json) {
57
+ console.log(JSON.stringify(status, null, 2));
58
+ return 0;
59
+ }
60
+ console.log(`Am I Cooked ${status.version}`);
61
+ console.log(` School: ${status.school ?? "not set up (run `amicooked setup`)"}`);
62
+ console.log(` Browser: ${status.browser ?? "not chosen yet"}`);
63
+ console.log(` Signed in: ${status.signedIn ? "yes" : "no (signs in again when needed, or run `amicooked login`)"}`);
64
+ console.log(` Claude Desktop: ${status.claudeDesktop}`);
65
+ console.log(` Claude Code: ${status.claudeCode}`);
66
+ console.log(` ChatGPT: ${status.chatgpt}`);
67
+ console.log(` Data: ${status.dataFolder}`);
68
+ console.log(` Files: ${status.filesFolder}`);
69
+ return 0;
70
+ }
71
+ export async function uninstallCommand(purge) {
72
+ const dir = claudeDesktopDir();
73
+ if (dir)
74
+ console.log(`Claude Desktop: ${uninstallClaudeDesktop(dir)}`);
75
+ if (hasClaudeCode()) {
76
+ uninstallClaudeCode();
77
+ console.log(`Claude Code: removed (skill ${uninstallSkill()})`);
78
+ }
79
+ if (uninstallChatGPT())
80
+ console.log("ChatGPT: background service stopped and disconnected");
81
+ if (purge) {
82
+ fs.rmSync(paths().home, { recursive: true, force: true });
83
+ console.log(`Deleted ${paths().home} (login, settings and file index). Downloaded files in ${getConfig().filesDir} were kept.`);
84
+ }
85
+ else {
86
+ console.log(`Kept your login and settings in ${paths().home}. Use --purge to delete them.`);
87
+ }
88
+ return 0;
89
+ }
@@ -0,0 +1,84 @@
1
+ import { spawn } from "child_process";
2
+ import { createRemoteServer, DEFAULT_PORT } from "../remote/http.js";
3
+ import { OAuthStore } from "../remote/oauth.js";
4
+ import { ensureCloudflared, ensureTunnel, heartbeat, readTunnel, startCloudflared } from "../remote/tunnel.js";
5
+ const HEARTBEAT_MS = 12 * 60 * 60 * 1000;
6
+ /** Keep the tunnel up, restarting cloudflared with a growing delay if it exits. */
7
+ function superviseTunnel(binary, tunnel) {
8
+ let delay = 2000;
9
+ const start = () => {
10
+ const child = startCloudflared(binary, tunnel);
11
+ const startedAt = Date.now();
12
+ child.stderr?.on("data", (d) => {
13
+ const line = String(d).trim();
14
+ if (/ERR|error/i.test(line))
15
+ console.error(`[tunnel] ${line.slice(0, 300)}`);
16
+ });
17
+ child.on("exit", (code) => {
18
+ if (Date.now() - startedAt > 60000)
19
+ delay = 2000;
20
+ console.error(`[tunnel] cloudflared exited (${code}); restarting in ${delay / 1000}s`);
21
+ setTimeout(start, delay);
22
+ delay = Math.min(delay * 2, 5 * 60 * 1000);
23
+ });
24
+ };
25
+ start();
26
+ }
27
+ /** Developer fallback: a throwaway trycloudflare.com URL instead of a provisioned tunnel. */
28
+ async function quickTunnel(binary, port) {
29
+ const child = spawn(binary, ["tunnel", "--no-autoupdate", "--url", `http://127.0.0.1:${port}`], { stdio: ["ignore", "ignore", "pipe"] });
30
+ const url = await new Promise((resolve, reject) => {
31
+ const timer = setTimeout(() => reject(new Error("cloudflared didn't report a URL")), 30000);
32
+ child.stderr.on("data", (d) => {
33
+ const match = String(d).match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
34
+ if (match)
35
+ clearTimeout(timer), resolve(match[0]);
36
+ });
37
+ child.on("exit", () => reject(new Error("cloudflared exited")));
38
+ });
39
+ return { url, child };
40
+ }
41
+ /** Keep a Mac from idle-sleeping while ChatGPT may need it; released when we exit. */
42
+ function keepAwake() {
43
+ if (process.platform !== "darwin")
44
+ return;
45
+ spawn("caffeinate", ["-i", "-w", String(process.pid)], { stdio: "ignore", detached: true }).unref();
46
+ }
47
+ export async function serveCommand(options) {
48
+ const port = options.port ?? DEFAULT_PORT;
49
+ let publicUrl = `http://127.0.0.1:${port}`;
50
+ let tunnel = null;
51
+ let quick = null;
52
+ if (options.quick) {
53
+ const q = await quickTunnel(await ensureCloudflared(), port);
54
+ publicUrl = q.url;
55
+ quick = q.child;
56
+ }
57
+ else if (!options.local) {
58
+ tunnel = readTunnel() ?? (await ensureTunnel());
59
+ publicUrl = tunnel.url;
60
+ }
61
+ const server = createRemoteServer({ publicUrl, store: new OAuthStore() });
62
+ await new Promise((resolve, reject) => {
63
+ server.once("error", reject);
64
+ server.listen(port, "127.0.0.1", resolve);
65
+ });
66
+ console.error(`[serve] listening on 127.0.0.1:${port}, public URL ${publicUrl}/mcp`);
67
+ if (tunnel) {
68
+ superviseTunnel(await ensureCloudflared(), tunnel);
69
+ await heartbeat(tunnel);
70
+ setInterval(() => heartbeat(tunnel), HEARTBEAT_MS).unref();
71
+ }
72
+ keepAwake();
73
+ const stop = () => {
74
+ quick?.kill();
75
+ server.close();
76
+ process.exit(0);
77
+ };
78
+ process.on("SIGINT", stop);
79
+ process.on("SIGTERM", stop);
80
+ if (options.quick) {
81
+ console.log(`ChatGPT connector URL (changes every run): ${publicUrl}/mcp\nPairing code: ${new OAuthStore().newPairingCode()}`);
82
+ }
83
+ return new Promise(() => { });
84
+ }