@almightygpt/core 0.7.2 → 0.8.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.
Files changed (41) hide show
  1. package/dist/adapters/claude.d.ts +8 -1
  2. package/dist/adapters/claude.d.ts.map +1 -1
  3. package/dist/adapters/claude.js +26 -7
  4. package/dist/adapters/claude.js.map +1 -1
  5. package/dist/adapters/gemini.d.ts +5 -1
  6. package/dist/adapters/gemini.d.ts.map +1 -1
  7. package/dist/adapters/gemini.js +23 -10
  8. package/dist/adapters/gemini.js.map +1 -1
  9. package/dist/adapters/openai.d.ts +6 -1
  10. package/dist/adapters/openai.d.ts.map +1 -1
  11. package/dist/adapters/openai.js +28 -16
  12. package/dist/adapters/openai.js.map +1 -1
  13. package/dist/auth/keychain.d.ts +30 -0
  14. package/dist/auth/keychain.d.ts.map +1 -0
  15. package/dist/auth/keychain.js +106 -0
  16. package/dist/auth/keychain.js.map +1 -0
  17. package/dist/auth/resolver.d.ts +32 -0
  18. package/dist/auth/resolver.d.ts.map +1 -0
  19. package/dist/auth/resolver.js +58 -0
  20. package/dist/auth/resolver.js.map +1 -0
  21. package/dist/auth/types.d.ts +45 -0
  22. package/dist/auth/types.d.ts.map +1 -0
  23. package/dist/auth/types.js +51 -0
  24. package/dist/auth/types.js.map +1 -0
  25. package/dist/auth/validator.d.ts +33 -0
  26. package/dist/auth/validator.d.ts.map +1 -0
  27. package/dist/auth/validator.js +130 -0
  28. package/dist/auth/validator.js.map +1 -0
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +6 -1
  32. package/dist/index.js.map +1 -1
  33. package/package.json +4 -1
  34. package/src/adapters/claude.ts +24 -7
  35. package/src/adapters/gemini.ts +21 -11
  36. package/src/adapters/openai.ts +26 -15
  37. package/src/auth/keychain.ts +132 -0
  38. package/src/auth/resolver.ts +81 -0
  39. package/src/auth/types.ts +68 -0
  40. package/src/auth/validator.ts +145 -0
  41. package/src/index.ts +22 -1
@@ -0,0 +1,132 @@
1
+ /**
2
+ * OS keychain wrapper — @napi-rs/keyring loaded via DYNAMIC IMPORT.
3
+ *
4
+ * The native binary is an OPTIONAL runtime capability:
5
+ * - If @napi-rs/keyring is installed and loads → real keychain access
6
+ * (macOS Keychain, Windows Credential Manager, Linux Secret Service).
7
+ * - If it's NOT installed (optionalDependencies skipped on exotic OS,
8
+ * or just plain missing) → returns an unavailable shim. Resolver
9
+ * falls through to env vars without crashing.
10
+ *
11
+ * This pattern means `npm install almightygpt` NEVER blocks on keychain
12
+ * binary failure. Codex's review explicitly flagged this as the
13
+ * correct strategy.
14
+ *
15
+ * Service name: `almightygpt` (consistent across all platforms; what
16
+ * users see in macOS Keychain Access.app, Windows credential UI, etc.)
17
+ */
18
+
19
+ import type { ProviderId } from "./types.js";
20
+
21
+ const KEYCHAIN_SERVICE = "almightygpt";
22
+
23
+ export interface KeychainAdapter {
24
+ available: boolean;
25
+ get(provider: ProviderId): Promise<string | undefined>;
26
+ set(provider: ProviderId, key: string): Promise<void>;
27
+ remove(provider: ProviderId): Promise<boolean>;
28
+ /** Optional diagnostic — backend name, or "unavailable". */
29
+ describeBackend(): string;
30
+ }
31
+
32
+ /**
33
+ * Lazy-loaded singleton. We never throw on import failure; instead the
34
+ * resulting adapter reports `available: false` and the resolver knows
35
+ * to skip it.
36
+ */
37
+ let cached: KeychainAdapter | null = null;
38
+
39
+ export async function getKeychain(): Promise<KeychainAdapter> {
40
+ if (cached) return cached;
41
+ cached = await loadKeychain();
42
+ return cached;
43
+ }
44
+
45
+ async function loadKeychain(): Promise<KeychainAdapter> {
46
+ try {
47
+ // Dynamic import — never crashes the module if the package is
48
+ // missing or its native binary fails to load on the host.
49
+ const mod = (await import("@napi-rs/keyring")) as {
50
+ Entry: new (service: string, account: string) => {
51
+ getPassword(): string | null;
52
+ setPassword(password: string): void;
53
+ deletePassword(): boolean;
54
+ };
55
+ };
56
+
57
+ const entryFor = (provider: ProviderId) =>
58
+ new mod.Entry(KEYCHAIN_SERVICE, provider);
59
+
60
+ // Probe: try to construct an Entry. If the native binding throws
61
+ // (no Secret Service daemon on Linux, etc.), we degrade.
62
+ try {
63
+ entryFor("openai");
64
+ } catch {
65
+ return makeUnavailable("native binding failed to initialize");
66
+ }
67
+
68
+ return {
69
+ available: true,
70
+ describeBackend: () => detectBackend(),
71
+ async get(provider) {
72
+ try {
73
+ const v = entryFor(provider).getPassword();
74
+ return v === null ? undefined : v;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ },
79
+ async set(provider, key) {
80
+ entryFor(provider).setPassword(key);
81
+ },
82
+ async remove(provider) {
83
+ try {
84
+ return entryFor(provider).deletePassword();
85
+ } catch {
86
+ return false;
87
+ }
88
+ },
89
+ };
90
+ } catch (err) {
91
+ return makeUnavailable(
92
+ err instanceof Error ? err.message : "import failed",
93
+ );
94
+ }
95
+ }
96
+
97
+ function makeUnavailable(reason: string): KeychainAdapter {
98
+ return {
99
+ available: false,
100
+ describeBackend: () => `unavailable (${reason})`,
101
+ async get() {
102
+ return undefined;
103
+ },
104
+ async set() {
105
+ throw new Error(
106
+ `Keychain unavailable: ${reason}. Set the API key via an environment ` +
107
+ `variable instead (e.g. ANTHROPIC_API_KEY).`,
108
+ );
109
+ },
110
+ async remove() {
111
+ return false;
112
+ },
113
+ };
114
+ }
115
+
116
+ function detectBackend(): string {
117
+ switch (process.platform) {
118
+ case "darwin":
119
+ return "macos-keychain";
120
+ case "win32":
121
+ return "windows-credential-manager";
122
+ case "linux":
123
+ return "linux-secret-service";
124
+ default:
125
+ return process.platform;
126
+ }
127
+ }
128
+
129
+ /** Exposed for tests that want to reset the singleton between cases. */
130
+ export function _resetKeychainCache(): void {
131
+ cached = null;
132
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * API key resolver — the single entry point every adapter must call
3
+ * to find its key. Replaces direct `process.env[...]` reads.
4
+ *
5
+ * Priority order (top to bottom):
6
+ * 1. Explicit parameter (caller passed a key — tests, extension handoff)
7
+ * 2. Environment variable (per-process override; wins over keychain)
8
+ * 3. OS keychain (persistent convenience; optional capability)
9
+ * 4. Missing → throw AuthMissingError
10
+ *
11
+ * Env wins over keychain by design — see types.ts header for the
12
+ * bug-class reasoning that drove the decision.
13
+ */
14
+
15
+ import { getKeychain } from "./keychain.js";
16
+ import {
17
+ AuthMissingError,
18
+ PROVIDER_ENV_VARS,
19
+ type KeyResolution,
20
+ type ProviderId,
21
+ } from "./types.js";
22
+
23
+ export interface ResolveOptions {
24
+ /** Optional caller-supplied key — wins over all other sources. */
25
+ explicit?: string;
26
+ /** Skip keychain lookup entirely (used by tests). */
27
+ skipKeychain?: boolean;
28
+ }
29
+
30
+ /**
31
+ * Resolve where the API key for `provider` lives.
32
+ * Returns a KeyResolution describing the source even when not found
33
+ * (caller can decide whether to throw).
34
+ */
35
+ export async function resolveApiKey(
36
+ provider: ProviderId,
37
+ options: ResolveOptions = {},
38
+ ): Promise<KeyResolution> {
39
+ // 1. Explicit override
40
+ if (options.explicit) {
41
+ return { provider, source: "explicit", key: options.explicit };
42
+ }
43
+
44
+ // 2. Environment variable
45
+ for (const envVar of PROVIDER_ENV_VARS[provider]) {
46
+ const v = process.env[envVar];
47
+ if (v && v.length > 0) {
48
+ return { provider, source: "env", key: v, envVar };
49
+ }
50
+ }
51
+
52
+ // 3. OS keychain (optional)
53
+ if (!options.skipKeychain) {
54
+ const keychain = await getKeychain();
55
+ if (keychain.available) {
56
+ const v = await keychain.get(provider);
57
+ if (v && v.length > 0) {
58
+ return { provider, source: "keychain", key: v };
59
+ }
60
+ }
61
+ }
62
+
63
+ // 4. Missing
64
+ return { provider, source: "missing" };
65
+ }
66
+
67
+ /**
68
+ * Convenience wrapper that throws AuthMissingError on absence — for
69
+ * callers (adapters) that need the key or can't proceed.
70
+ */
71
+ export async function requireApiKey(
72
+ provider: ProviderId,
73
+ options: ResolveOptions = {},
74
+ ): Promise<string> {
75
+ const resolved = await resolveApiKey(provider, options);
76
+ if (resolved.source === "missing") {
77
+ const primaryEnv = PROVIDER_ENV_VARS[provider][0]!;
78
+ throw new AuthMissingError(provider, primaryEnv);
79
+ }
80
+ return resolved.key!;
81
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Auth subsystem types — provider identifiers, resolution sources,
3
+ * error classes.
4
+ *
5
+ * The auth module's job is to answer one question per call:
6
+ * "where is the API key for <provider>, and what is it?"
7
+ *
8
+ * Resolution priority (top to bottom):
9
+ * 1. Explicit parameter (passed by caller — tests, extension handoff)
10
+ * 2. Environment variable (per-process override; wins over keychain)
11
+ * 3. OS keychain (persistent convenience; @napi-rs/keyring optional)
12
+ * 4. Missing -> throw AuthMissingError
13
+ *
14
+ * Env-wins-over-keychain is intentional. The original draft had the
15
+ * order flipped; Codex's independent review caught that it would
16
+ * silently override the VS Code extension's freshly-stored key with
17
+ * a stale keychain copy. See docs/claude/v0.8-auth-plan.md.
18
+ */
19
+
20
+ export type ProviderId = "openai" | "anthropic" | "google";
21
+
22
+ export type KeySource = "explicit" | "env" | "keychain" | "missing";
23
+
24
+ export interface KeyResolution {
25
+ provider: ProviderId;
26
+ source: KeySource;
27
+ /** Present iff source !== "missing". */
28
+ key?: string;
29
+ /** Which env var was used (only set when source === "env"). */
30
+ envVar?: string;
31
+ }
32
+
33
+ /**
34
+ * Thrown when no key is found in any source. Caller should surface
35
+ * the message verbatim — it tells the user exactly how to fix it.
36
+ */
37
+ export class AuthMissingError extends Error {
38
+ readonly provider: ProviderId;
39
+ readonly envVar: string;
40
+ constructor(provider: ProviderId, envVar: string) {
41
+ super(
42
+ `No API key found for ${provider}. ` +
43
+ `Run "almightygpt auth ${provider}" to set one up interactively, ` +
44
+ `or export ${envVar} in your shell.`,
45
+ );
46
+ this.name = "AuthMissingError";
47
+ this.provider = provider;
48
+ this.envVar = envVar;
49
+ }
50
+ }
51
+
52
+ /** Maps each provider to the canonical env var name(s) we read. */
53
+ export const PROVIDER_ENV_VARS: Record<ProviderId, readonly string[]> = {
54
+ openai: ["OPENAI_API_KEY"],
55
+ anthropic: ["ANTHROPIC_API_KEY"],
56
+ // Google's SDK historically accepted both names; honor both.
57
+ google: ["GOOGLE_API_KEY", "GEMINI_API_KEY"],
58
+ };
59
+
60
+ /**
61
+ * Browser-launchable URL where a user creates / manages keys for each
62
+ * provider. Used by the `almightygpt auth <provider>` flow.
63
+ */
64
+ export const PROVIDER_KEY_URLS: Record<ProviderId, string> = {
65
+ openai: "https://platform.openai.com/api-keys",
66
+ anthropic: "https://console.anthropic.com/settings/keys",
67
+ google: "https://aistudio.google.com/apikey",
68
+ };
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Model-level key validation.
3
+ *
4
+ * Codex's review caught that listing models (e.g. `GET /v1/models`) can
5
+ * succeed when the key lacks model permission, has quota issues, or
6
+ * has billing-state problems. The user doesn't care that list-models
7
+ * works — they care that AlmightyGPT can run the configured review
8
+ * model.
9
+ *
10
+ * So we validate with the same operation class real reviews use:
11
+ * - OpenAI: tiny chat completion against gpt-4o
12
+ * - Anthropic: tiny messages call against claude-sonnet-4-6
13
+ * - Google: tiny generateContent call against gemini-2.5-flash
14
+ *
15
+ * Cost is fractions of a cent per call. Latency is ~1-3 seconds.
16
+ * Failure surfaces the provider's exact error message so the user
17
+ * can fix it.
18
+ */
19
+
20
+ import type { ProviderId } from "./types.js";
21
+
22
+ export interface ValidationResult {
23
+ ok: boolean;
24
+ /** Provider-reported model used (e.g. "gpt-4o-2024-08-06"). */
25
+ model?: string;
26
+ /** Provider's error message verbatim if ok === false. */
27
+ error?: string;
28
+ }
29
+
30
+ const DEFAULT_VALIDATION_MODELS: Record<ProviderId, string> = {
31
+ openai: "gpt-4o",
32
+ anthropic: "claude-sonnet-4-6",
33
+ google: "gemini-2.5-flash",
34
+ };
35
+
36
+ const VALIDATION_TIMEOUT_MS = 15_000;
37
+
38
+ /**
39
+ * Validate that a key can actually invoke the model real reviews use.
40
+ * Returns a result object — never throws on validation failure (only
41
+ * on programmer errors like an unsupported provider).
42
+ */
43
+ export async function validateKey(
44
+ provider: ProviderId,
45
+ key: string,
46
+ ): Promise<ValidationResult> {
47
+ try {
48
+ switch (provider) {
49
+ case "openai":
50
+ return await validateOpenAI(key);
51
+ case "anthropic":
52
+ return await validateAnthropic(key);
53
+ case "google":
54
+ return await validateGoogle(key);
55
+ }
56
+ } catch (err) {
57
+ return {
58
+ ok: false,
59
+ error: err instanceof Error ? err.message : String(err),
60
+ };
61
+ }
62
+ }
63
+
64
+ async function validateOpenAI(key: string): Promise<ValidationResult> {
65
+ const model = DEFAULT_VALIDATION_MODELS.openai;
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), VALIDATION_TIMEOUT_MS);
68
+ try {
69
+ const res = await fetch("https://api.openai.com/v1/chat/completions", {
70
+ method: "POST",
71
+ headers: {
72
+ "content-type": "application/json",
73
+ authorization: `Bearer ${key}`,
74
+ },
75
+ body: JSON.stringify({
76
+ model,
77
+ messages: [{ role: "user", content: "hi" }],
78
+ max_tokens: 1,
79
+ }),
80
+ signal: controller.signal,
81
+ });
82
+ if (!res.ok) {
83
+ return { ok: false, error: await res.text().catch(() => res.statusText) };
84
+ }
85
+ const data = (await res.json()) as { model?: string };
86
+ return { ok: true, model: data.model ?? model };
87
+ } finally {
88
+ clearTimeout(timer);
89
+ }
90
+ }
91
+
92
+ async function validateAnthropic(key: string): Promise<ValidationResult> {
93
+ const model = DEFAULT_VALIDATION_MODELS.anthropic;
94
+ const controller = new AbortController();
95
+ const timer = setTimeout(() => controller.abort(), VALIDATION_TIMEOUT_MS);
96
+ try {
97
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
98
+ method: "POST",
99
+ headers: {
100
+ "content-type": "application/json",
101
+ "x-api-key": key,
102
+ "anthropic-version": "2023-06-01",
103
+ },
104
+ body: JSON.stringify({
105
+ model,
106
+ max_tokens: 5,
107
+ messages: [{ role: "user", content: "hi" }],
108
+ }),
109
+ signal: controller.signal,
110
+ });
111
+ if (!res.ok) {
112
+ return { ok: false, error: await res.text().catch(() => res.statusText) };
113
+ }
114
+ const data = (await res.json()) as { model?: string };
115
+ return { ok: true, model: data.model ?? model };
116
+ } finally {
117
+ clearTimeout(timer);
118
+ }
119
+ }
120
+
121
+ async function validateGoogle(key: string): Promise<ValidationResult> {
122
+ const model = DEFAULT_VALIDATION_MODELS.google;
123
+ const controller = new AbortController();
124
+ const timer = setTimeout(() => controller.abort(), VALIDATION_TIMEOUT_MS);
125
+ try {
126
+ const url =
127
+ `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=` +
128
+ encodeURIComponent(key);
129
+ const res = await fetch(url, {
130
+ method: "POST",
131
+ headers: { "content-type": "application/json" },
132
+ body: JSON.stringify({
133
+ contents: [{ parts: [{ text: "hi" }] }],
134
+ generationConfig: { maxOutputTokens: 5 },
135
+ }),
136
+ signal: controller.signal,
137
+ });
138
+ if (!res.ok) {
139
+ return { ok: false, error: await res.text().catch(() => res.statusText) };
140
+ }
141
+ return { ok: true, model };
142
+ } finally {
143
+ clearTimeout(timer);
144
+ }
145
+ }
package/src/index.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * - budget/ ✅ task #14 BudgetTracker + BudgetExceededError
14
14
  */
15
15
 
16
- export const VERSION = "0.7.2";
16
+ export const VERSION = "0.8.0";
17
17
 
18
18
  // Git safety primitives
19
19
  export {
@@ -127,3 +127,24 @@ export type {
127
127
  ReviewEventHandler,
128
128
  AgentRoleInRun,
129
129
  } from "./review/events.js";
130
+
131
+ // Auth subsystem (v0.8.0+) — resolver, keychain, validator
132
+ export {
133
+ resolveApiKey,
134
+ requireApiKey,
135
+ type ResolveOptions,
136
+ } from "./auth/resolver.js";
137
+ export {
138
+ getKeychain,
139
+ _resetKeychainCache,
140
+ type KeychainAdapter,
141
+ } from "./auth/keychain.js";
142
+ export { validateKey, type ValidationResult } from "./auth/validator.js";
143
+ export {
144
+ AuthMissingError,
145
+ PROVIDER_ENV_VARS,
146
+ PROVIDER_KEY_URLS,
147
+ type ProviderId,
148
+ type KeySource,
149
+ type KeyResolution,
150
+ } from "./auth/types.js";