aegiscode 6.7.8 → 6.8.1

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.
@@ -46,6 +46,25 @@ function envVar(name) {
46
46
  return v && !/^\$\{[A-Z_]+\}$/.test(v) ? v : '';
47
47
  }
48
48
 
49
+ /**
50
+ * Read a positive millisecond count from the environment, or 0 for "unset".
51
+ *
52
+ * Used only for the two stream watchdogs below. Non-positive and unparseable
53
+ * values are IGNORED rather than honoured — deliberately not the rule the
54
+ * engine's host cooldown uses, where `AEGIS_HOST_COOLDOWN_MS=0` meaning "no
55
+ * cooldown" is a coherent thing to ask for. Here `0` would mean "the stream is
56
+ * dead before its first byte", which is a typo rather than a preference, and
57
+ * silently killing every turn is a far worse failure than ignoring a bad
58
+ * number. A test that genuinely wants a sub-second watchdog passes
59
+ * `idleTimeoutMs` per call (test/autonomous-mode.test.mjs does exactly that).
60
+ */
61
+ function envIdleMs(name) {
62
+ const raw = envVar(name);
63
+ if (!raw) return 0;
64
+ const n = Number(raw);
65
+ return Number.isFinite(n) && n > 0 ? n : 0;
66
+ }
67
+
49
68
  /**
50
69
  * UUID v4 that works everywhere: Web Crypto first (browsers, Node ≥ 19),
51
70
  * then Node's CJS crypto module (Node < 19), then a Math.random fallback for
@@ -895,9 +914,27 @@ const BRAIN_IDLE_TIMEOUT_MS = 15 * 60_000;
895
914
  * that runs the fan-out, so a renamed brain id or a caller that forgot its
896
915
  * flag cannot desynchronise the two. A response with no header (an older
897
916
  * server, or a single-pass call) keeps the caller's budget or the 60s default.
917
+ *
918
+ * ── the two env knobs ───────────────────────────────────────────────────────
919
+ *
920
+ * `AEGIS_SSE_IDLE_TIMEOUT_MS` and `AEGIS_BRAIN_IDLE_TIMEOUT_MS` move those two
921
+ * *defaults* without a code edit: the CLI is a host, not a fork, so before this
922
+ * the only way to give a slow link more room — or to reproduce a stall against
923
+ * a fixed wedged server — was to patch the transport. Same escape hatch the
924
+ * engine gives its host cooldown (`AEGIS_HOST_COOLDOWN_MS`).
925
+ *
926
+ * Both are read at CALL time, not at module load, so a host that sets one after
927
+ * `require()` still gets it, and one that unsets it is back on the shipped
928
+ * default. A per-call `idleTimeoutMs` still outranks both: an explicit number
929
+ * from the caller is a decision about *this* request, while the env var is only
930
+ * a house default. See envIdleMs() for why a bad value is ignored rather than
931
+ * obeyed.
898
932
  */
899
933
  function idleBudgetFor(res, requestedMs) {
900
- const base = Number(requestedMs) > 0 ? Number(requestedMs) : SSE_IDLE_TIMEOUT_MS;
934
+ // Caller override -> env knob -> shipped default.
935
+ const stated = Number(requestedMs);
936
+ const envDefault = envIdleMs('AEGIS_SSE_IDLE_TIMEOUT_MS');
937
+ const base = stated > 0 ? stated : envDefault > 0 ? envDefault : SSE_IDLE_TIMEOUT_MS;
901
938
  let header = '';
902
939
  try {
903
940
  const get = res && res.headers && typeof res.headers.get === 'function' ? res.headers.get.bind(res.headers) : null;
@@ -905,7 +942,13 @@ function idleBudgetFor(res, requestedMs) {
905
942
  } catch {
906
943
  header = ''; // an exotic fetch shim without headers: keep the caller's budget
907
944
  }
908
- return header && String(header).trim() ? Math.max(base, BRAIN_IDLE_TIMEOUT_MS) : base;
945
+ // The fan-out floor is tunable for the same reason the base is — and it has
946
+ // to stay a FLOOR: a server that announced workers=3 is still working, so a
947
+ // smaller base must not cut it off. Raise both if the server's own
948
+ // NEXUS_BRAIN_WORKER_TIMEOUT moves (test/autonomous-mode.test.mjs pins the
949
+ // 600s relationship between them).
950
+ const brainFloor = envIdleMs('AEGIS_BRAIN_IDLE_TIMEOUT_MS') || BRAIN_IDLE_TIMEOUT_MS;
951
+ return header && String(header).trim() ? Math.max(base, brainFloor) : base;
909
952
  }
910
953
 
911
954
  const api = { createClient, envVar, randomUUID, DEFAULT_API_BASE, CLIENT_VERSION, idleBudgetFor, SSE_IDLE_TIMEOUT_MS, BRAIN_IDLE_TIMEOUT_MS };
@@ -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
+ };