aegiscode 6.7.8 → 6.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.
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The shared `~/.aegiscode/.env` loader.
5
+ *
6
+ * One file holding every key this product family can use, for every host:
7
+ *
8
+ * AEGIS_API_KEY=aegis_…
9
+ * OPENAI_API_KEY=sk-…
10
+ * DEEPSEEK_API_KEY=sk-…
11
+ *
12
+ * Before this module each host read `process.env` only, which meant a key was
13
+ * configured if — and only if — the user had exported it in the shell that
14
+ * happened to launch the app. That is why the byok flow needed a separate
15
+ * `/byok-key <provider>` step and an encrypted per-provider store: the file was
16
+ * never read. Reading it into `process.env` at startup makes the instruction
17
+ * the same in the CLI and the desktop — "put it in ~/.aegiscode/.env" — and it
18
+ * needs no other change in either, because `AEGIS_API_KEY` is already the FIRST
19
+ * entry in `client/credentials.js`'s documented resolution order.
20
+ *
21
+ * Two rules this module deliberately obeys:
22
+ *
23
+ * 1. A variable already present in the environment is never overwritten. The
24
+ * file is a convenience for the common case, not a way for a stale file to
25
+ * shadow an explicit `AEGIS_API_KEY=… aegiscode` in CI.
26
+ * 2. It reads only. Nothing here writes a secret, so the 0600 store remains
27
+ * the one thing this repo creates; if the file the user made is readable
28
+ * by other accounts we say so rather than fixing it silently.
29
+ */
30
+
31
+ const fs = require('node:fs');
32
+ const path = require('node:path');
33
+ const credentials = require('./credentials.js');
34
+
35
+ const ENV_FILE = '.env';
36
+
37
+ /**
38
+ * provider id -> the env var a BYOK key is conventionally exported as, for the
39
+ * ids where the generic rule below would spell the wrong name. The generic rule
40
+ * is `ID_API_KEY` in upper snake case, which already covers openai, anthropic,
41
+ * deepseek, groq, mistral, openrouter, together and most of the catalogue — so
42
+ * this table is only the exceptions, kept short on purpose.
43
+ */
44
+ const ALIASES = Object.freeze({
45
+ google: 'GEMINI_API_KEY',
46
+ gemini: 'GEMINI_API_KEY',
47
+ 'google-ai': 'GEMINI_API_KEY',
48
+ xai: 'XAI_API_KEY',
49
+ 'x-ai': 'XAI_API_KEY',
50
+ grok: 'XAI_API_KEY',
51
+ huggingface: 'HF_TOKEN',
52
+ together: 'TOGETHER_API_KEY',
53
+ 'together-ai': 'TOGETHER_API_KEY',
54
+ fireworks: 'FIREWORKS_API_KEY',
55
+ 'azure-openai': 'AZURE_OPENAI_API_KEY',
56
+ 'voyage-ai': 'VOYAGE_API_KEY',
57
+ });
58
+
59
+ /** The file this host would read, honouring `$AEGISCODE_HOME`. */
60
+ function envFileFor(dir) {
61
+ return path.join(dir || credentials.aegisHome(), ENV_FILE);
62
+ }
63
+
64
+ /**
65
+ * The env var one BYOK provider's key is read from.
66
+ *
67
+ * @param {string} providerId e.g. 'openai', 'deepseek', 'Google'
68
+ * @returns {string} e.g. 'OPENAI_API_KEY' — '' when there is no usable id
69
+ */
70
+ function envVarFor(providerId) {
71
+ const id = String(providerId || '').trim().toLowerCase();
72
+ if (!id) return '';
73
+ // A `byok:` prefixed row is the same provider — accept it so callers can pass
74
+ // whatever spelling they hold without stripping it first.
75
+ const bare = id.startsWith('byok:') ? id.slice('byok:'.length).trim() : id;
76
+ if (!bare) return '';
77
+ if (ALIASES[bare]) return ALIASES[bare];
78
+ const name = bare.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
79
+ return name ? `${name}_API_KEY` : '';
80
+ }
81
+
82
+ /**
83
+ * Parse dotenv text. Deliberately small and total: an unparseable line is
84
+ * skipped rather than thrown, so one bad line cannot stop the rest of the file
85
+ * (and a stray `#` comment or a blank line is normal, not an error).
86
+ *
87
+ * Handles `export `, `KEY=value`, `KEY="value"`, `KEY='value'` and a trailing
88
+ * ` # comment` on an unquoted value.
89
+ */
90
+ function parseEnvText(text) {
91
+ const out = {};
92
+ for (const raw of String(text == null ? '' : text).split(/\r?\n/)) {
93
+ const line = raw.trim();
94
+ if (!line || line.startsWith('#')) continue;
95
+ const eq = line.indexOf('=');
96
+ if (eq <= 0) continue;
97
+ let name = line.slice(0, eq).trim();
98
+ if (name.startsWith('export ')) name = name.slice('export '.length).trim();
99
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
100
+ let value = line.slice(eq + 1).trim();
101
+ const quoted = (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
102
+ || (value.startsWith("'") && value.endsWith("'") && value.length >= 2);
103
+ if (quoted) {
104
+ value = value.slice(1, -1);
105
+ } else {
106
+ const hash = value.indexOf(' #');
107
+ if (hash !== -1) value = value.slice(0, hash).trim();
108
+ }
109
+ out[name] = value;
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /**
115
+ * Read the env file into `process.env` (or `o.env`), without overwriting
116
+ * anything already set.
117
+ *
118
+ * @param {object} [o]
119
+ * @param {object} [o.env] defaults to process.env
120
+ * @param {string} [o.dir] defaults to aegisHome()
121
+ * @param {string} [o.file] an explicit path, for tests
122
+ * @returns {{ok:boolean, file:string, loaded:string[], kept:string[],
123
+ * reason:string, loose:boolean, mode:number}}
124
+ * `loaded` — names taken from the file. `kept` — names the environment
125
+ * already had, left alone (a real export always wins).
126
+ */
127
+ function loadEnvFile(o = {}) {
128
+ const env = o.env || process.env;
129
+ const file = o.file || envFileFor(o.dir);
130
+ const result = { ok: false, file, loaded: [], kept: [], reason: '', loose: false, mode: 0 };
131
+
132
+ let text;
133
+ try {
134
+ text = fs.readFileSync(file, 'utf8');
135
+ } catch (e) {
136
+ result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
137
+ return result;
138
+ }
139
+
140
+ try {
141
+ const st = fs.statSync(file);
142
+ result.mode = st.mode & 0o777;
143
+ // Group- or world-readable: worth one line to the user, never a rewrite of
144
+ // a file we did not create.
145
+ result.loose = (st.mode & 0o077) !== 0;
146
+ } catch { /* stat is advisory only */ }
147
+
148
+ const parsed = parseEnvText(text);
149
+ for (const [name, value] of Object.entries(parsed)) {
150
+ if (env[name] === undefined || env[name] === '') {
151
+ env[name] = value;
152
+ result.loaded.push(name);
153
+ } else {
154
+ result.kept.push(name);
155
+ }
156
+ }
157
+ result.ok = true;
158
+ return result;
159
+ }
160
+
161
+ /**
162
+ * The BYOK key for a provider out of the environment, if the env file (or the
163
+ * shell) supplies one. Returns '' when it does not — the encrypted store then
164
+ * remains the only source, exactly as before.
165
+ */
166
+ function providerKeyFromEnv(providerId, env) {
167
+ const name = envVarFor(providerId);
168
+ if (!name) return { key: '', env: '' };
169
+ const raw = (env || process.env)[name];
170
+ const key = typeof raw === 'string' ? raw.trim() : '';
171
+ return { key, env: name };
172
+ }
173
+
174
+ module.exports = {
175
+ ENV_FILE,
176
+ ALIASES,
177
+ envFileFor,
178
+ envVarFor,
179
+ parseEnvText,
180
+ loadEnvFile,
181
+ providerKeyFromEnv,
182
+ };