codemaxxing 1.0.16 → 1.1.0

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,214 @@
1
+ import { detectHardware } from "../utils/hardware.js";
2
+ import { getRecommendationsWithLlmfit } from "../utils/models.js";
3
+ import { isOllamaInstalled, isOllamaRunning, startOllama, pullModel, getOllamaInstallCommand } from "../utils/ollama.js";
4
+ import { openRouterOAuth } from "../utils/auth.js";
5
+ export function handleWizardScreen(_inputChar, key, ctx) {
6
+ if (!ctx.wizardScreen)
7
+ return false;
8
+ if (ctx.wizardScreen === "connection") {
9
+ const items = ["local", "openrouter", "apikey", "existing"];
10
+ if (key.upArrow) {
11
+ ctx.setWizardIndex((prev) => (prev - 1 + items.length) % items.length);
12
+ return true;
13
+ }
14
+ if (key.downArrow) {
15
+ ctx.setWizardIndex((prev) => (prev + 1) % items.length);
16
+ return true;
17
+ }
18
+ if (key.escape) {
19
+ ctx.setWizardScreen(null);
20
+ return true;
21
+ }
22
+ if (key.return) {
23
+ const selected = items[ctx.wizardIndex];
24
+ if (selected === "local") {
25
+ const hw = detectHardware();
26
+ ctx.setWizardHardware(hw);
27
+ const { models: recs } = getRecommendationsWithLlmfit(hw);
28
+ ctx.setWizardModels(recs.filter(m => m.fit !== "skip"));
29
+ ctx.setWizardScreen("models");
30
+ ctx.setWizardIndex(() => 0);
31
+ }
32
+ else if (selected === "openrouter") {
33
+ ctx.setWizardScreen(null);
34
+ ctx.addMsg("info", "Starting OpenRouter OAuth — opening browser...");
35
+ ctx.setLoading(true);
36
+ ctx.setSpinnerMsg("Waiting for authorization...");
37
+ openRouterOAuth((msg) => ctx.addMsg("info", msg))
38
+ .then(() => {
39
+ ctx.addMsg("info", "✅ OpenRouter authenticated! Use /connect to connect.");
40
+ ctx.setLoading(false);
41
+ })
42
+ .catch((err) => { ctx.addMsg("error", `OAuth failed: ${err.message}`); ctx.setLoading(false); });
43
+ }
44
+ else if (selected === "apikey") {
45
+ ctx.setWizardScreen(null);
46
+ ctx.setLoginPicker(true);
47
+ ctx.setLoginPickerIndex(() => 0);
48
+ }
49
+ else if (selected === "existing") {
50
+ ctx.setWizardScreen(null);
51
+ ctx.addMsg("info", "Start your LLM server, then type /connect to retry.");
52
+ }
53
+ return true;
54
+ }
55
+ return true;
56
+ }
57
+ if (ctx.wizardScreen === "models") {
58
+ const models = ctx.wizardModels;
59
+ if (key.upArrow) {
60
+ ctx.setWizardIndex((prev) => (prev - 1 + models.length) % models.length);
61
+ return true;
62
+ }
63
+ if (key.downArrow) {
64
+ ctx.setWizardIndex((prev) => (prev + 1) % models.length);
65
+ return true;
66
+ }
67
+ if (key.escape) {
68
+ ctx.setWizardScreen("connection");
69
+ ctx.setWizardIndex(() => 0);
70
+ return true;
71
+ }
72
+ if (key.return) {
73
+ const selected = models[ctx.wizardIndex];
74
+ if (selected) {
75
+ ctx.setWizardSelectedModel(selected);
76
+ if (!isOllamaInstalled()) {
77
+ ctx.setWizardScreen("install-ollama");
78
+ }
79
+ else {
80
+ startPullFlow(ctx, selected);
81
+ }
82
+ }
83
+ return true;
84
+ }
85
+ return true;
86
+ }
87
+ if (ctx.wizardScreen === "install-ollama") {
88
+ if (key.escape) {
89
+ ctx.setWizardScreen("models");
90
+ ctx.setWizardIndex(() => 0);
91
+ return true;
92
+ }
93
+ if (key.return) {
94
+ if (!isOllamaInstalled()) {
95
+ ctx.setLoading(true);
96
+ ctx.setSpinnerMsg("Installing Ollama... this may take a minute");
97
+ const installCmd = getOllamaInstallCommand(ctx.wizardHardware?.os ?? "linux");
98
+ (async () => {
99
+ try {
100
+ const { exec } = ctx._require("child_process");
101
+ await new Promise((resolve, reject) => {
102
+ exec(installCmd, { timeout: 180000 }, (err, _stdout, stderr) => {
103
+ if (err)
104
+ reject(new Error(stderr || err.message));
105
+ else
106
+ resolve();
107
+ });
108
+ });
109
+ ctx.addMsg("info", "✅ Ollama installed! Proceeding to model download...");
110
+ ctx.setLoading(false);
111
+ await new Promise(r => setTimeout(r, 2000));
112
+ ctx.setWizardScreen("models");
113
+ }
114
+ catch (e) {
115
+ ctx.addMsg("error", `Install failed: ${e.message}`);
116
+ ctx.addMsg("info", `Try manually in a separate terminal: ${installCmd}`);
117
+ ctx.setLoading(false);
118
+ ctx.setWizardScreen("install-ollama");
119
+ }
120
+ })();
121
+ return true;
122
+ }
123
+ // Ollama already installed — proceed to pull
124
+ {
125
+ const selected = ctx.wizardSelectedModel;
126
+ if (selected) {
127
+ startPullFlow(ctx, selected);
128
+ }
129
+ }
130
+ return true;
131
+ }
132
+ return true;
133
+ }
134
+ if (ctx.wizardScreen === "pulling") {
135
+ if (ctx.wizardPullError && key.return) {
136
+ const selected = ctx.wizardSelectedModel;
137
+ if (selected) {
138
+ ctx.setWizardPullError(null);
139
+ ctx.setWizardPullProgress({ status: "retrying", percent: 0 });
140
+ (async () => {
141
+ try {
142
+ const running = await isOllamaRunning();
143
+ if (!running) {
144
+ startOllama();
145
+ for (let i = 0; i < 15; i++) {
146
+ await new Promise(r => setTimeout(r, 1000));
147
+ if (await isOllamaRunning())
148
+ break;
149
+ }
150
+ }
151
+ await pullModel(selected.ollamaId, (p) => ctx.setWizardPullProgress(p));
152
+ ctx.setWizardPullProgress({ status: "success", percent: 100 });
153
+ await new Promise(r => setTimeout(r, 500));
154
+ ctx.setWizardScreen(null);
155
+ ctx.setWizardPullProgress(null);
156
+ ctx.setWizardSelectedModel(null);
157
+ ctx.addMsg("info", `✅ ${selected.name} installed! Connecting...`);
158
+ await ctx.connectToProvider(true);
159
+ }
160
+ catch (err) {
161
+ ctx.setWizardPullError(err.message);
162
+ }
163
+ })();
164
+ }
165
+ return true;
166
+ }
167
+ if (ctx.wizardPullError && key.escape) {
168
+ ctx.setWizardScreen("models");
169
+ ctx.setWizardIndex(() => 0);
170
+ ctx.setWizardPullError(null);
171
+ ctx.setWizardPullProgress(null);
172
+ return true;
173
+ }
174
+ return true; // Ignore keys while pulling
175
+ }
176
+ return true;
177
+ }
178
+ // ── Shared pull-model flow ──
179
+ function startPullFlow(ctx, selected) {
180
+ ctx.setWizardScreen("pulling");
181
+ ctx.setWizardPullProgress({ status: "starting", percent: 0 });
182
+ ctx.setWizardPullError(null);
183
+ (async () => {
184
+ try {
185
+ const running = await isOllamaRunning();
186
+ if (!running) {
187
+ ctx.setWizardPullProgress({ status: "Starting Ollama server...", percent: 0 });
188
+ startOllama();
189
+ for (let i = 0; i < 15; i++) {
190
+ await new Promise(r => setTimeout(r, 1000));
191
+ if (await isOllamaRunning())
192
+ break;
193
+ }
194
+ if (!(await isOllamaRunning())) {
195
+ ctx.setWizardPullError("Could not start Ollama server. Run 'ollama serve' manually, then press Enter.");
196
+ return;
197
+ }
198
+ }
199
+ await pullModel(selected.ollamaId, (p) => {
200
+ ctx.setWizardPullProgress(p);
201
+ });
202
+ ctx.setWizardPullProgress({ status: "success", percent: 100 });
203
+ await new Promise(r => setTimeout(r, 500));
204
+ ctx.setWizardScreen(null);
205
+ ctx.setWizardPullProgress(null);
206
+ ctx.setWizardSelectedModel(null);
207
+ ctx.addMsg("info", `✅ ${selected.name} installed! Connecting...`);
208
+ await ctx.connectToProvider(true);
209
+ }
210
+ catch (err) {
211
+ ctx.setWizardPullError(err.message);
212
+ }
213
+ })();
214
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Anthropic OAuth PKCE flow
3
+ *
4
+ * Lets users log in with their Claude Pro/Max subscription (no API key needed).
5
+ * Uses the same OAuth flow as Claude Code CLI.
6
+ */
7
+ import { type AuthCredential } from "./auth.js";
8
+ export declare function refreshAnthropicOAuthToken(refreshToken: string): Promise<{
9
+ access: string;
10
+ refresh: string;
11
+ expires: number;
12
+ }>;
13
+ export declare function loginAnthropicOAuth(onStatus?: (msg: string) => void): Promise<AuthCredential>;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Anthropic OAuth PKCE flow
3
+ *
4
+ * Lets users log in with their Claude Pro/Max subscription (no API key needed).
5
+ * Uses the same OAuth flow as Claude Code CLI.
6
+ */
7
+ import { createServer } from "http";
8
+ import { randomBytes, createHash } from "crypto";
9
+ import { exec } from "child_process";
10
+ import { saveCredential } from "./auth.js";
11
+ // ── Constants ──
12
+ const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
13
+ const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
14
+ const TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
15
+ const CALLBACK_HOST = "127.0.0.1";
16
+ const CALLBACK_PORT = 53692;
17
+ const CALLBACK_PATH = "/callback";
18
+ const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
19
+ const SCOPES = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
20
+ // ── PKCE helpers ──
21
+ function base64url(buf) {
22
+ return buf
23
+ .toString("base64")
24
+ .replace(/\+/g, "-")
25
+ .replace(/\//g, "_")
26
+ .replace(/=/g, "");
27
+ }
28
+ function generatePKCE() {
29
+ const verifier = base64url(randomBytes(32));
30
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
31
+ return { verifier, challenge };
32
+ }
33
+ // ── Browser opener ──
34
+ function openBrowser(url) {
35
+ const cmd = process.platform === "darwin"
36
+ ? `open "${url}"`
37
+ : process.platform === "win32"
38
+ ? `start "" "${url}"`
39
+ : `xdg-open "${url}"`;
40
+ exec(cmd);
41
+ }
42
+ // ── Token refresh ──
43
+ export async function refreshAnthropicOAuthToken(refreshToken) {
44
+ const res = await fetch(TOKEN_URL, {
45
+ method: "POST",
46
+ headers: { "Content-Type": "application/json" },
47
+ body: JSON.stringify({
48
+ grant_type: "refresh_token",
49
+ client_id: CLIENT_ID,
50
+ refresh_token: refreshToken,
51
+ scope: SCOPES,
52
+ }),
53
+ });
54
+ if (!res.ok) {
55
+ const errText = await res.text();
56
+ throw new Error(`Token refresh failed (${res.status}): ${errText}`);
57
+ }
58
+ const data = (await res.json());
59
+ return {
60
+ access: data.access_token,
61
+ refresh: data.refresh_token ?? refreshToken,
62
+ expires: Date.now() + data.expires_in * 1000,
63
+ };
64
+ }
65
+ // ── Main OAuth login flow ──
66
+ export async function loginAnthropicOAuth(onStatus) {
67
+ const { verifier, challenge } = generatePKCE();
68
+ return new Promise((resolve, reject) => {
69
+ const server = createServer(async (req, res) => {
70
+ const url = new URL(req.url ?? "/", "http://localhost");
71
+ if (url.pathname !== CALLBACK_PATH) {
72
+ res.writeHead(404);
73
+ res.end("Not found");
74
+ return;
75
+ }
76
+ const code = url.searchParams.get("code");
77
+ const returnedState = url.searchParams.get("state");
78
+ if (!code) {
79
+ res.writeHead(400, { "Content-Type": "text/html" });
80
+ res.end("<h1>Error: No authorization code received</h1><p>Please try again.</p>");
81
+ server.close();
82
+ reject(new Error("No authorization code received"));
83
+ return;
84
+ }
85
+ // state should match verifier
86
+ if (returnedState !== verifier) {
87
+ res.writeHead(400, { "Content-Type": "text/html" });
88
+ res.end("<h1>Error: State mismatch</h1><p>Please try again.</p>");
89
+ server.close();
90
+ reject(new Error("OAuth state mismatch"));
91
+ return;
92
+ }
93
+ onStatus?.("Exchanging code for tokens...");
94
+ try {
95
+ const tokenRes = await fetch(TOKEN_URL, {
96
+ method: "POST",
97
+ headers: { "Content-Type": "application/json" },
98
+ body: JSON.stringify({
99
+ grant_type: "authorization_code",
100
+ client_id: CLIENT_ID,
101
+ code,
102
+ state: verifier,
103
+ redirect_uri: REDIRECT_URI,
104
+ code_verifier: verifier,
105
+ }),
106
+ });
107
+ if (!tokenRes.ok) {
108
+ const errText = await tokenRes.text();
109
+ throw new Error(`Token exchange failed (${tokenRes.status}): ${errText}`);
110
+ }
111
+ const tokenData = (await tokenRes.json());
112
+ res.writeHead(200, { "Content-Type": "text/html" });
113
+ res.end("<html><body style=\"font-family:monospace;background:#1a1a2e;color:#0ff;display:flex;justify-content:center;align-items:center;height:100vh;margin:0\"><div style=\"text-align:center\"><h1>Authenticated!</h1><p>You can close this tab and return to Codemaxxing.</p></div></body></html>");
114
+ server.close();
115
+ const expiresAt = Date.now() + tokenData.expires_in * 1000;
116
+ const cred = {
117
+ provider: "anthropic",
118
+ method: "oauth",
119
+ apiKey: tokenData.access_token,
120
+ baseUrl: "https://api.anthropic.com",
121
+ label: "Anthropic (Claude Pro/Max)",
122
+ refreshToken: tokenData.refresh_token,
123
+ oauthExpires: expiresAt,
124
+ createdAt: new Date().toISOString(),
125
+ };
126
+ saveCredential(cred);
127
+ resolve(cred);
128
+ }
129
+ catch (err) {
130
+ res.writeHead(500, { "Content-Type": "text/html" });
131
+ res.end(`<h1>Error</h1><p>${err.message}</p>`);
132
+ server.close();
133
+ reject(err);
134
+ }
135
+ });
136
+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
137
+ const params = new URLSearchParams({
138
+ code: "true",
139
+ client_id: CLIENT_ID,
140
+ response_type: "code",
141
+ redirect_uri: REDIRECT_URI,
142
+ scope: SCOPES,
143
+ code_challenge: challenge,
144
+ code_challenge_method: "S256",
145
+ state: verifier,
146
+ });
147
+ const authUrl = `${AUTHORIZE_URL}?${params.toString()}`;
148
+ onStatus?.("Opening browser for Claude login...");
149
+ try {
150
+ openBrowser(authUrl);
151
+ }
152
+ catch {
153
+ onStatus?.(`Could not open browser. Please visit:\n${authUrl}`);
154
+ }
155
+ onStatus?.("Waiting for authorization...");
156
+ // Timeout after 120 seconds
157
+ setTimeout(() => {
158
+ server.close();
159
+ reject(new Error("OAuth timed out after 120 seconds"));
160
+ }, 120 * 1000);
161
+ });
162
+ server.on("error", (err) => {
163
+ if (err.code === "EADDRINUSE") {
164
+ reject(new Error(`Port ${CALLBACK_PORT} is already in use. Close other auth flows and try again.`));
165
+ }
166
+ else {
167
+ reject(err);
168
+ }
169
+ });
170
+ });
171
+ }
@@ -18,6 +18,8 @@ export interface AuthCredential {
18
18
  baseUrl: string;
19
19
  label?: string;
20
20
  expiresAt?: string;
21
+ refreshToken?: string;
22
+ oauthExpires?: number;
21
23
  createdAt: string;
22
24
  }
23
25
  export interface ProviderDef {
@@ -17,6 +17,7 @@ import { join } from "path";
17
17
  import { createServer } from "http";
18
18
  import { randomBytes, createHash } from "crypto";
19
19
  import { execSync, exec } from "child_process";
20
+ import { detectOpenAICodexOAuth } from "./openai-oauth.js";
20
21
  // ── Paths ──
21
22
  const CONFIG_DIR = join(homedir(), ".codemaxxing");
22
23
  const AUTH_FILE = join(CONFIG_DIR, "auth.json");
@@ -32,15 +33,15 @@ export const PROVIDERS = [
32
33
  {
33
34
  id: "anthropic",
34
35
  name: "Anthropic (Claude)",
35
- methods: ["setup-token", "api-key"],
36
- baseUrl: "https://api.anthropic.com/v1",
36
+ methods: ["oauth", "api-key"],
37
+ baseUrl: "https://api.anthropic.com",
37
38
  consoleUrl: "https://console.anthropic.com/settings/keys",
38
39
  description: "Claude Opus, Sonnet, Haiku — use your subscription or API key",
39
40
  },
40
41
  {
41
42
  id: "openai",
42
43
  name: "OpenAI (ChatGPT)",
43
- methods: ["cached-token", "api-key"],
44
+ methods: ["oauth", "api-key"],
44
45
  baseUrl: "https://api.openai.com/v1",
45
46
  consoleUrl: "https://platform.openai.com/api-keys",
46
47
  description: "GPT-4o, GPT-5, o1 — use your ChatGPT subscription or API key",
@@ -291,6 +292,16 @@ export async function anthropicSetupToken(onStatus) {
291
292
  }
292
293
  // ── OpenAI / Codex CLI Cached Token ──
293
294
  export function detectCodexToken() {
295
+ // Check OpenClaw auth-profiles first (for Codex OAuth tokens)
296
+ try {
297
+ const oauthCreds = detectOpenAICodexOAuth();
298
+ if (oauthCreds?.access) {
299
+ return oauthCreds.access;
300
+ }
301
+ }
302
+ catch {
303
+ // detection failed, fall through
304
+ }
294
305
  // Codex CLI stores OAuth tokens — check common locations
295
306
  const locations = [
296
307
  join(homedir(), ".codex", "auth.json"),
@@ -314,6 +325,28 @@ export function detectCodexToken() {
314
325
  }
315
326
  }
316
327
  }
328
+ // Codex CLI v0.18+ stores tokens in macOS Keychain
329
+ if (process.platform === "darwin") {
330
+ const keychainQueries = [
331
+ ["security", "find-generic-password", "-s", "codex", "-w"],
332
+ ["security", "find-generic-password", "-a", "openai", "-s", "codex", "-w"],
333
+ ["security", "find-generic-password", "-s", "openai-codex", "-w"],
334
+ ["security", "find-generic-password", "-l", "codex", "-w"],
335
+ ];
336
+ for (const args of keychainQueries) {
337
+ try {
338
+ const token = execSync(args.join(" "), { stdio: "pipe", timeout: 3000 }).toString().trim();
339
+ if (token)
340
+ return token;
341
+ }
342
+ catch {
343
+ continue;
344
+ }
345
+ }
346
+ }
347
+ // Final fallback: environment variable
348
+ if (process.env.OPENAI_API_KEY)
349
+ return process.env.OPENAI_API_KEY;
317
350
  return null;
318
351
  }
319
352
  export function importCodexToken(onStatus) {
@@ -467,6 +500,12 @@ export function detectAvailableAuth() {
467
500
  description: "Claude Code CLI detected — can link your Anthropic subscription",
468
501
  });
469
502
  }
503
+ // OpenAI: always offer OAuth login, and note if cached tokens exist
504
+ available.push({
505
+ provider: "openai",
506
+ method: "oauth",
507
+ description: "Log in with your ChatGPT subscription (browser OAuth)",
508
+ });
470
509
  if (detectCodexToken()) {
471
510
  available.push({
472
511
  provider: "openai",
@@ -25,6 +25,11 @@ export function isOllamaInstalled() {
25
25
  if (getWindowsOllamaPaths().some(p => existsSync(p)))
26
26
  return true;
27
27
  }
28
+ // Check known install paths on macOS
29
+ if (process.platform === "darwin") {
30
+ if (existsSync("/usr/local/bin/ollama") || existsSync("/opt/homebrew/bin/ollama"))
31
+ return true;
32
+ }
28
33
  // Check if the server is responding (if server is running, Ollama is definitely installed)
29
34
  try {
30
35
  execSync("curl -s http://localhost:11434/api/tags", {
@@ -64,7 +69,7 @@ export async function isOllamaRunning() {
64
69
  /** Get the install command for the user's OS */
65
70
  export function getOllamaInstallCommand(os) {
66
71
  switch (os) {
67
- case "macos": return "brew install ollama";
72
+ case "macos": return "curl -fsSL https://ollama.com/install.sh | sh";
68
73
  case "linux": return "curl -fsSL https://ollama.com/install.sh | sh";
69
74
  case "windows": return "winget install Ollama.Ollama";
70
75
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * OpenAI Codex OAuth PKCE flow
3
+ *
4
+ * Lets users log in with their ChatGPT Plus/Pro subscription (no API key needed).
5
+ * Uses the same OAuth flow as OpenAI's Codex CLI.
6
+ */
7
+ import { type AuthCredential } from "./auth.js";
8
+ export declare function detectOpenAICodexOAuth(): {
9
+ access: string;
10
+ refresh: string;
11
+ expires: number;
12
+ accountId: string;
13
+ } | null;
14
+ export declare function refreshOpenAICodexToken(refreshToken: string): Promise<{
15
+ access: string;
16
+ refresh: string;
17
+ expires: number;
18
+ }>;
19
+ export declare function loginOpenAICodexOAuth(onStatus?: (msg: string) => void): Promise<AuthCredential>;