aegiscode 7.0.7 → 7.0.9
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/package.json +3 -2
- package/src/app.js +164 -13
- package/src/chatflow.js +135 -10
- package/src/commands.js +240 -11
- package/src/deps.js +28 -2
- package/src/engine.js +8 -1
- package/src/models.js +78 -3
- package/src/render.js +9 -1
- package/vendor/client/aegis.js +122 -3
- package/vendor/client/auto-provision.js +42 -3
- package/vendor/client/credentials.js +8 -2
- package/vendor/client/env-file.js +262 -8
- package/vendor/client/user-models.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +872 -0
- package/vendor/desktop/lib/local/engine.js +444 -16
- package/vendor/desktop/renderer/usage.js +25 -6
- package/vendor/one/src/child.js +287 -0
- package/vendor/one/src/permissions.js +371 -0
package/vendor/client/aegis.js
CHANGED
|
@@ -448,6 +448,24 @@ const DEFAULT_TIMEOUT_MS = 60000;
|
|
|
448
448
|
*/
|
|
449
449
|
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
|
450
450
|
|
|
451
|
+
/**
|
|
452
|
+
* 429 back-off. aegis1 rate-limits the BYOK relay per IP —
|
|
453
|
+
* `rate_limit(f"byok:{ip}", max_calls=20, window=60)` in app.py — so a single
|
|
454
|
+
* agentic turn (24–48 tool rounds, each one a relay call) bursts straight
|
|
455
|
+
* through 20 requests in a minute and the turn dies mid-flight on a message
|
|
456
|
+
* the user reads as a broken backend. The limit is the server's to set; what
|
|
457
|
+
* this transport owes the caller is to treat a 429 as "slow down", not as a
|
|
458
|
+
* fatal turn.
|
|
459
|
+
*
|
|
460
|
+
* Retries are bounded and the wait is capped, because the alternative to a
|
|
461
|
+
* bounded back-off is a turn that hangs forever on a window that never opens.
|
|
462
|
+
*/
|
|
463
|
+
const RATE_LIMIT_RETRIES = 4;
|
|
464
|
+
/** Ceiling on a single wait, so a hostile/huge `Retry-After` cannot hang a turn. */
|
|
465
|
+
const RATE_LIMIT_MAX_WAIT_MS = 30000;
|
|
466
|
+
/** Base for the exponential fallback when the server sends no `Retry-After`. */
|
|
467
|
+
const RATE_LIMIT_BASE_WAIT_MS = 1000;
|
|
468
|
+
|
|
451
469
|
/**
|
|
452
470
|
* .mcp.json / Electron pass config as "${VAR}" template refs. When the var is
|
|
453
471
|
* unset, hosts have been observed to leave the template literally unexpanded
|
|
@@ -556,6 +574,87 @@ function createClient(opts = {}) {
|
|
|
556
574
|
}
|
|
557
575
|
}
|
|
558
576
|
|
|
577
|
+
/**
|
|
578
|
+
* How long to hold off after a 429. The server's `Retry-After` wins when it
|
|
579
|
+
* sends one, since only the server knows when the window actually opens; both
|
|
580
|
+
* the delta-seconds and the HTTP-date form are accepted because either is
|
|
581
|
+
* legal. Without the header — which is the case for aegis1's BYOK relay today,
|
|
582
|
+
* it answers the bare 429 body — we back off exponentially from
|
|
583
|
+
* RATE_LIMIT_BASE_WAIT_MS. Either way the wait is capped: an unclamped
|
|
584
|
+
* `Retry-After` (or a hostile one) would otherwise be a turn that hangs.
|
|
585
|
+
*/
|
|
586
|
+
function rateLimitDelayMs(res, attempt) {
|
|
587
|
+
const header =
|
|
588
|
+
res && res.headers && typeof res.headers.get === 'function'
|
|
589
|
+
? res.headers.get('retry-after')
|
|
590
|
+
: null;
|
|
591
|
+
let delay = 0;
|
|
592
|
+
if (header) {
|
|
593
|
+
const secs = Number(header);
|
|
594
|
+
if (Number.isFinite(secs) && secs >= 0) {
|
|
595
|
+
delay = secs * 1000;
|
|
596
|
+
} else {
|
|
597
|
+
const when = Date.parse(header);
|
|
598
|
+
if (Number.isFinite(when)) delay = when - Date.now();
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (!delay) delay = rateLimitBaseWaitMs * Math.pow(2, attempt);
|
|
602
|
+
return Math.min(delay, rateLimitMaxWaitMs);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Wait out a back-off. A mid-wait abort resolves rather than rejecting: the
|
|
607
|
+
* retry that follows is issued on the caller's now-aborted signal, so `fetch`
|
|
608
|
+
* rejects the way it would have anyway. Synthesising a second abort error here
|
|
609
|
+
* would race the real one to the caller's catch and decide which of the two
|
|
610
|
+
* they see — not this helper's call to make.
|
|
611
|
+
*/
|
|
612
|
+
function sleep(ms, signal) {
|
|
613
|
+
return new Promise((resolve) => {
|
|
614
|
+
const timer = setTimeout(resolve, ms);
|
|
615
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
616
|
+
if (!signal || typeof signal.addEventListener !== 'function') return;
|
|
617
|
+
if (signal.aborted) {
|
|
618
|
+
clearTimeout(timer);
|
|
619
|
+
resolve();
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
signal.addEventListener(
|
|
623
|
+
'abort',
|
|
624
|
+
() => {
|
|
625
|
+
clearTimeout(timer);
|
|
626
|
+
resolve();
|
|
627
|
+
},
|
|
628
|
+
{ once: true }
|
|
629
|
+
);
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* `boundedFetch` with a 429 back-off. Retries are bounded (RATE_LIMIT_RETRIES)
|
|
635
|
+
* so a window that never opens still fails — and fails with the server's own
|
|
636
|
+
* 429 body, since the last response is returned unread to `parseResponse`
|
|
637
|
+
* rather than being replaced by a home-made "gave up" error. The caller keeps
|
|
638
|
+
* the message the user was already seeing; it just arrives after the transport
|
|
639
|
+
* did what it could.
|
|
640
|
+
*/
|
|
641
|
+
async function fetchWithRateLimitRetry(url, init) {
|
|
642
|
+
let res = await boundedFetch(url, init);
|
|
643
|
+
for (let attempt = 0; res && res.status === 429 && attempt < rateLimitRetries; attempt++) {
|
|
644
|
+
const wait = rateLimitDelayMs(res, attempt);
|
|
645
|
+
try {
|
|
646
|
+
// The 429 body is discarded unread either way — releasing it is what
|
|
647
|
+
// keeps a long back-off from pinning the socket.
|
|
648
|
+
if (res.body) await res.body.cancel();
|
|
649
|
+
} catch {
|
|
650
|
+
/* discarded anyway */
|
|
651
|
+
}
|
|
652
|
+
await sleep(wait, init && init.signal);
|
|
653
|
+
res = await boundedFetch(url, init);
|
|
654
|
+
}
|
|
655
|
+
return res;
|
|
656
|
+
}
|
|
657
|
+
|
|
559
658
|
/** Read a response body, refusing to buffer more than MAX_BODY_BYTES. */
|
|
560
659
|
async function readCappedText(res) {
|
|
561
660
|
if (!res || !res.body || typeof res.body.getReader !== 'function') {
|
|
@@ -609,6 +708,20 @@ function createClient(opts = {}) {
|
|
|
609
708
|
: DEFAULT_TIMEOUT_MS;
|
|
610
709
|
const maxBodyBytes =
|
|
611
710
|
Number(opts.maxBodyBytes) > 0 ? Number(opts.maxBodyBytes) : MAX_BODY_BYTES;
|
|
711
|
+
// The 429 back-off is injectable for the same reason as the two ceilings
|
|
712
|
+
// above: a guard that can only be exercised by sleeping out a real
|
|
713
|
+
// 15-second window is a guard that quietly rots. Defaults are the production
|
|
714
|
+
// values (the RATE_LIMIT_* constants at the top of this module).
|
|
715
|
+
const rateLimitRetries =
|
|
716
|
+
Number(opts.rateLimitRetries) >= 0 ? Number(opts.rateLimitRetries) : RATE_LIMIT_RETRIES;
|
|
717
|
+
const rateLimitBaseWaitMs =
|
|
718
|
+
Number(opts.rateLimitBaseWaitMs) >= 0
|
|
719
|
+
? Number(opts.rateLimitBaseWaitMs)
|
|
720
|
+
: RATE_LIMIT_BASE_WAIT_MS;
|
|
721
|
+
const rateLimitMaxWaitMs =
|
|
722
|
+
Number(opts.rateLimitMaxWaitMs) > 0
|
|
723
|
+
? Number(opts.rateLimitMaxWaitMs)
|
|
724
|
+
: RATE_LIMIT_MAX_WAIT_MS;
|
|
612
725
|
|
|
613
726
|
/**
|
|
614
727
|
* A campaign-tagged upgrade link. Never hand-build a `/subscribe` URL in a
|
|
@@ -657,7 +770,7 @@ function createClient(opts = {}) {
|
|
|
657
770
|
}
|
|
658
771
|
|
|
659
772
|
async function apiPost(path, body, headers, opts) {
|
|
660
|
-
const res = await
|
|
773
|
+
const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, {
|
|
661
774
|
method: 'POST',
|
|
662
775
|
headers: headers || authHeaders(),
|
|
663
776
|
body: JSON.stringify(body || {}),
|
|
@@ -667,7 +780,7 @@ function createClient(opts = {}) {
|
|
|
667
780
|
}
|
|
668
781
|
|
|
669
782
|
async function apiGet(path, headers, opts) {
|
|
670
|
-
const res = await
|
|
783
|
+
const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, {
|
|
671
784
|
method: 'GET',
|
|
672
785
|
headers: headers || authHeaders(),
|
|
673
786
|
signal: opts && opts.signal,
|
|
@@ -1020,6 +1133,7 @@ function createClient(opts = {}) {
|
|
|
1020
1133
|
onStream,
|
|
1021
1134
|
signal,
|
|
1022
1135
|
providerKey,
|
|
1136
|
+
baseURL,
|
|
1023
1137
|
} = {}) {
|
|
1024
1138
|
const key = providerKey !== undefined ? providerKey : opts.providerKey;
|
|
1025
1139
|
// Same rule as the pooled path above: omit `max_tokens` entirely when the
|
|
@@ -1056,6 +1170,11 @@ function createClient(opts = {}) {
|
|
|
1056
1170
|
// `tools: []` differently from the field's plain absence.
|
|
1057
1171
|
...(Array.isArray(tools) && tools.length ? { tools } : {}),
|
|
1058
1172
|
...(toolChoice ? { tool_choice: toolChoice } : {}),
|
|
1173
|
+
// Read server-side ONLY for provider "custom" (aegis1 app.py
|
|
1174
|
+
// byok_chat_completions) — every other provider's upstream host is a
|
|
1175
|
+
// constant the server already knows, so sending this for them is a
|
|
1176
|
+
// no-op rather than a behaviour change.
|
|
1177
|
+
...(baseURL ? { base_url: baseURL } : {}),
|
|
1059
1178
|
};
|
|
1060
1179
|
if (model) body.model = model;
|
|
1061
1180
|
const headers = {
|
|
@@ -1126,7 +1245,7 @@ function createClient(opts = {}) {
|
|
|
1126
1245
|
// the gap the idle watchdog cannot reach — a server that accepts the
|
|
1127
1246
|
// socket and never sends response headers, where `reader.read()` has not
|
|
1128
1247
|
// been reached yet and so nothing is watching at all.
|
|
1129
|
-
|
|
1248
|
+
fetchWithRateLimitRetry(`${apiBase}${path}`, {
|
|
1130
1249
|
method: 'POST',
|
|
1131
1250
|
headers,
|
|
1132
1251
|
body: JSON.stringify({ ...payload, stream: true }),
|
|
@@ -53,18 +53,49 @@ function provisionFailureText(result) {
|
|
|
53
53
|
return `the server refused the request (HTTP ${err.status})`;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
// What to say about the welcome trial after a successful registration — or ''
|
|
57
|
+
// when there is nothing worth saying. Shared by every host so the CLI's two
|
|
58
|
+
// notice sites and the desktop cannot describe the same outcome in three
|
|
59
|
+
// different ways, which is how the reused case went unmentioned for so long.
|
|
60
|
+
//
|
|
61
|
+
// The two clauses are mutually exclusive in practice (the server only sends
|
|
62
|
+
// `trial_granted: false` on the new-fingerprint path, and `reused_account` only
|
|
63
|
+
// on the idempotent one) but `reusedAccount` is checked first: if they ever
|
|
64
|
+
// collide, "you already have this account" is the true statement, and a
|
|
65
|
+
// throttling claim would be a lie about a machine that was never throttled.
|
|
66
|
+
function trialOutcomeNote(result) {
|
|
67
|
+
if (result && result.reusedAccount) {
|
|
68
|
+
return '. This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.';
|
|
69
|
+
}
|
|
70
|
+
if (result && result.trialGranted === false) {
|
|
71
|
+
return '. The welcome trial was withheld this hour (too many new devices from this network)';
|
|
72
|
+
}
|
|
73
|
+
return '';
|
|
74
|
+
}
|
|
75
|
+
|
|
56
76
|
/**
|
|
57
77
|
* @param {object} aegisClient A client from client/aegis.js (createClient()).
|
|
58
78
|
* @param {object} credentials client/credentials.js (or a compatible double).
|
|
59
79
|
* @param {{app?: string, retryDelaysMs?: number[]}} [options] `app` names the host
|
|
60
80
|
* for the server's presence panel; `retryDelaysMs` waits before each retry of a
|
|
61
81
|
* transient failure.
|
|
62
|
-
* @returns {Promise<{ok: boolean, key: string, trialGranted?: boolean, error?: Error}>}
|
|
82
|
+
* @returns {Promise<{ok: boolean, key: string, trialGranted?: boolean, reusedAccount?: boolean, error?: Error}>}
|
|
63
83
|
* `ok` is true only when a usable key was obtained AND persisted to the
|
|
64
84
|
* shared store; `aegisClient.setApiKey()` has already been called on
|
|
65
85
|
* success, so the caller's client is immediately usable either way it
|
|
66
86
|
* inspects `ok`. `trialGranted` is false when the server withheld the
|
|
67
87
|
* welcome trial (the account and key are still valid).
|
|
88
|
+
*
|
|
89
|
+
* `reusedAccount` is the third outcome, and the one that used to be
|
|
90
|
+
* indistinguishable from a plain first install: this fingerprint was already
|
|
91
|
+
* registered, so aegis1 handed back the SAME account (aegis1 commit 2e2bd85
|
|
92
|
+
* added the `reused_account` field for exactly this). No trial is granted on
|
|
93
|
+
* that path and none can be — the welcome credit is once per machine, ever —
|
|
94
|
+
* and the server deliberately OMITS `trial_granted` there rather than
|
|
95
|
+
* sending false, so `trialGranted` stays `undefined`. Hosts must therefore
|
|
96
|
+
* branch on `reusedAccount`, not on `trialGranted`: reading an absent
|
|
97
|
+
* `trial_granted` as "not reused" is what left a wiped credential store
|
|
98
|
+
* showing a first-install notice over a returning account.
|
|
68
99
|
*/
|
|
69
100
|
async function autoProvisionApiKey(aegisClient, credentials, options = {}) {
|
|
70
101
|
if (Array.isArray(options)) {
|
|
@@ -83,7 +114,9 @@ async function autoProvisionApiKey(aegisClient, credentials, options = {}) {
|
|
|
83
114
|
if (!key) return { ok: false, key: '' };
|
|
84
115
|
const saved = credentials.saveApiKey(key);
|
|
85
116
|
aegisClient.setApiKey(key);
|
|
86
|
-
|
|
117
|
+
// `=== true` on purpose: an older aegis1 that predates `reused_account`
|
|
118
|
+
// sends nothing, and unknown must not read as reused.
|
|
119
|
+
return { ok: !!saved.ok, key, trialGranted: data.trial_granted, reusedAccount: data.reused_account === true };
|
|
87
120
|
} catch (err) {
|
|
88
121
|
lastError = err;
|
|
89
122
|
if (!isTransientRegisterError(err)) break;
|
|
@@ -94,4 +127,10 @@ async function autoProvisionApiKey(aegisClient, credentials, options = {}) {
|
|
|
94
127
|
return { ok: false, key: '', error: lastError };
|
|
95
128
|
}
|
|
96
129
|
|
|
97
|
-
module.exports = {
|
|
130
|
+
module.exports = {
|
|
131
|
+
autoProvisionApiKey,
|
|
132
|
+
provisionFailureText,
|
|
133
|
+
trialOutcomeNote,
|
|
134
|
+
DEVICE_REGISTER_TIMEOUT_MS,
|
|
135
|
+
DEVICE_REGISTER_RETRY_DELAYS_MS,
|
|
136
|
+
};
|
|
@@ -104,8 +104,14 @@ function normalizeApiKey(raw) {
|
|
|
104
104
|
* Shape check only — no network. Catches the two mistakes that are structural
|
|
105
105
|
* (an empty paste, and a wrapped/truncated multi-line paste) so the caller can
|
|
106
106
|
* refuse before spending a verification round trip.
|
|
107
|
+
*
|
|
108
|
+
* `o.label` names the credential in the "too short" message ("AEGIS keys",
|
|
109
|
+
* "Anthropic keys", …) — every caller sees the same 16-char floor, worded for
|
|
110
|
+
* whichever secret it is collecting. Defaults to 'AEGIS' so the one call site
|
|
111
|
+
* this shipped with (the account-key login flow) reads exactly as before.
|
|
107
112
|
*/
|
|
108
|
-
function validateApiKey(raw) {
|
|
113
|
+
function validateApiKey(raw, o = {}) {
|
|
114
|
+
const label = String(o.label || 'AEGIS');
|
|
109
115
|
const key = normalizeApiKey(raw);
|
|
110
116
|
if (!key) return { ok: false, key, reason: 'empty', message: 'no key given' };
|
|
111
117
|
if (/\s/.test(key)) {
|
|
@@ -121,7 +127,7 @@ function validateApiKey(raw) {
|
|
|
121
127
|
ok: false,
|
|
122
128
|
key,
|
|
123
129
|
reason: 'too short',
|
|
124
|
-
message: `that key is ${key.length} characters —
|
|
130
|
+
message: `that key is ${key.length} characters — ${label} keys are longer than that`,
|
|
125
131
|
};
|
|
126
132
|
}
|
|
127
133
|
return { ok: true, key, reason: null, message: null };
|
|
@@ -215,6 +215,59 @@ function envVarFor(providerId) {
|
|
|
215
215
|
return name ? `${name}_API_KEY` : '';
|
|
216
216
|
}
|
|
217
217
|
|
|
218
|
+
/** A fragment of a token/secret: no whitespace, no dotenv punctuation around it. */
|
|
219
|
+
const ENV_TOKENISH = /^[A-Za-z0-9_+/.-]+$/;
|
|
220
|
+
|
|
221
|
+
/** A value long enough that a keyless line after it is a wrap, not junk. */
|
|
222
|
+
const ENV_WRAP_MIN_VALUE = 32;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Fold a hard-wrapped value back onto its `KEY=` line.
|
|
226
|
+
*
|
|
227
|
+
* A long secret pasted into a wrapping editor leaves its tail on the next
|
|
228
|
+
* physical line. Dotenv semantics would keep the head as the value and discard
|
|
229
|
+
* the keyless tail, so the credential loads as a TRUNCATED string that looks
|
|
230
|
+
* present and fails deep in a provider call — a 108-char Claude Code OAuth
|
|
231
|
+
* token lost its last 9 chars this way and every request 401'd with "OAuth
|
|
232
|
+
* access token is invalid" while the env var looked set.
|
|
233
|
+
*
|
|
234
|
+
* A fold requires the tail to be unambiguously a token fragment: no whitespace,
|
|
235
|
+
* no `=`, not a comment, and either indented (the wrap signature a wrapped paste
|
|
236
|
+
* leaves behind) or following a value already long enough to be a secret. The
|
|
237
|
+
* head must itself be a plain unquoted token, so an inline ` # comment` can
|
|
238
|
+
* never be glued to the next line. A short value plus a bare word ("x" then
|
|
239
|
+
* "NOEQ") is left alone — that is a junk line, and gluing it on would corrupt
|
|
240
|
+
* the real value.
|
|
241
|
+
*
|
|
242
|
+
* @param {string[]} lines every physical line of the file
|
|
243
|
+
* @param {number} i index of the `KEY=` line
|
|
244
|
+
* @param {string} head the trimmed value on that line
|
|
245
|
+
* @returns {{value:string, i:number}} the folded value and the last line consumed
|
|
246
|
+
*/
|
|
247
|
+
function foldWrappedEnvValue(lines, i, head) {
|
|
248
|
+
let value = head;
|
|
249
|
+
// Only an unquoted, comment-free, token-shaped head may absorb a tail: any
|
|
250
|
+
// other head is a value with structure worth preserving verbatim.
|
|
251
|
+
if (value.startsWith('"') || value.startsWith("'")) return { value, i };
|
|
252
|
+
while (i + 1 < lines.length) {
|
|
253
|
+
const nextRaw = lines[i + 1];
|
|
254
|
+
const next = nextRaw.trim();
|
|
255
|
+
if (!next || next.startsWith('#') || next.includes('=')) break;
|
|
256
|
+
if (!ENV_TOKENISH.test(next)) break;
|
|
257
|
+
const indented = /^[ \t]/.test(nextRaw);
|
|
258
|
+
// The non-indented branch is the risky one (a bare word after a value), so
|
|
259
|
+
// it additionally demands the head be one unbroken token AND long enough to
|
|
260
|
+
// be a secret before it is allowed to swallow the line.
|
|
261
|
+
if (!indented && (value.length < ENV_WRAP_MIN_VALUE || !ENV_TOKENISH.test(value))) break;
|
|
262
|
+
value += next;
|
|
263
|
+
i += 1;
|
|
264
|
+
// Once a tail has been absorbed the head is only longer, so a further
|
|
265
|
+
// indented fragment keeps folding; a non-indented one now clears the length
|
|
266
|
+
// bar on its own.
|
|
267
|
+
}
|
|
268
|
+
return { value, i };
|
|
269
|
+
}
|
|
270
|
+
|
|
218
271
|
/**
|
|
219
272
|
* Parse dotenv text. Deliberately small and total: an unparseable line is
|
|
220
273
|
* skipped rather than thrown, so one bad line cannot stop the rest of the file
|
|
@@ -224,18 +277,28 @@ function envVarFor(providerId) {
|
|
|
224
277
|
* ` # comment` on an unquoted value. A double-quoted value is unescaped (`\"`,
|
|
225
278
|
* `\\`) because that is what `quoteEnvValue` writes and what dotenv readers do;
|
|
226
279
|
* a single-quoted value is literal.
|
|
280
|
+
*
|
|
281
|
+
* A hard-wrapped paste is folded back together (see `foldWrappedEnvValue`).
|
|
282
|
+
* This is not cosmetic: a 108-char Claude Code OAuth token pasted into a
|
|
283
|
+
* wrapping editor landed as a 99-char head plus an indented keyless tail, and
|
|
284
|
+
* the head loaded as a TRUNCATED credential that looked present and 401'd deep
|
|
285
|
+
* in a provider call. The same fold exists in `src/env.js` of the engine repo
|
|
286
|
+
* (`parseEnvFile`) so both readers agree on a wrapped file.
|
|
227
287
|
*/
|
|
228
288
|
function parseEnvText(text) {
|
|
229
289
|
const out = {};
|
|
230
|
-
|
|
231
|
-
|
|
290
|
+
const lines = String(text == null ? '' : text).split(/\r?\n/);
|
|
291
|
+
for (let i = 0; i < lines.length; i++) {
|
|
292
|
+
const line = lines[i].trim();
|
|
232
293
|
if (!line || line.startsWith('#')) continue;
|
|
233
294
|
const eq = line.indexOf('=');
|
|
234
295
|
if (eq <= 0) continue;
|
|
235
296
|
let name = line.slice(0, eq).trim();
|
|
236
297
|
if (name.startsWith('export ')) name = name.slice('export '.length).trim();
|
|
237
298
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
|
|
238
|
-
|
|
299
|
+
const folded = foldWrappedEnvValue(lines, i, line.slice(eq + 1).trim());
|
|
300
|
+
let value = folded.value;
|
|
301
|
+
i = folded.i;
|
|
239
302
|
const doubleQuoted = value.startsWith('"') && value.endsWith('"') && value.length >= 2;
|
|
240
303
|
const singleQuoted = value.startsWith("'") && value.endsWith("'") && value.length >= 2;
|
|
241
304
|
if (doubleQuoted) {
|
|
@@ -447,6 +510,45 @@ function foreignSecretValue(name, o = {}) {
|
|
|
447
510
|
}
|
|
448
511
|
}
|
|
449
512
|
|
|
513
|
+
/**
|
|
514
|
+
* One foreign secret's value, from every place a user might actually have put
|
|
515
|
+
* it — built for `CLAUDE_CODE_OAUTH_TOKEN`, which lived in plain `.env` before
|
|
516
|
+
* this split existed and is not necessarily migrated on any given machine.
|
|
517
|
+
*
|
|
518
|
+
* Checked in the order that keeps an explicit export authoritative, same as
|
|
519
|
+
* `loadEnvFile`'s rule 1:
|
|
520
|
+
*
|
|
521
|
+
* 1. `o.env` (default `process.env`) — a real shell export is the user's own
|
|
522
|
+
* doing and always wins, exactly as it does for a host key.
|
|
523
|
+
* 2. `secrets.env` (`foreignSecretValue`) — the file the split moves this
|
|
524
|
+
* name to, and the only one `setForeignSecret` below ever writes.
|
|
525
|
+
* 3. `.env`, parsed directly — covers a name that has not been migrated yet.
|
|
526
|
+
*
|
|
527
|
+
* Never applies the value to any env object: the whole point of the split is
|
|
528
|
+
* that this name stays OUT of `process.env` unless the caller that actually
|
|
529
|
+
* needs it (the Claude Code Pro transport) asks for it by name, right before
|
|
530
|
+
* it is used.
|
|
531
|
+
*
|
|
532
|
+
* @param {string} name
|
|
533
|
+
* @param {object} [o] `env`, `dir`, `file` — same meaning as `foreignSecretValue`
|
|
534
|
+
* @returns {string} '' when no source has it, or `name` is not a foreign secret
|
|
535
|
+
*/
|
|
536
|
+
function resolveForeignSecret(name, o = {}) {
|
|
537
|
+
if (!isForeignSecret(name)) return '';
|
|
538
|
+
const env = o.env || process.env;
|
|
539
|
+
const direct = env && env[name];
|
|
540
|
+
if (typeof direct === 'string' && direct.trim()) return direct.trim();
|
|
541
|
+
const fromSecrets = foreignSecretValue(name, o);
|
|
542
|
+
if (fromSecrets && fromSecrets.trim()) return fromSecrets.trim();
|
|
543
|
+
try {
|
|
544
|
+
const parsed = parseEnvText(fs.readFileSync(envFileFor(o.dir), 'utf8'));
|
|
545
|
+
const v = parsed[String(name)];
|
|
546
|
+
return typeof v === 'string' ? v.trim() : '';
|
|
547
|
+
} catch {
|
|
548
|
+
return '';
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
450
552
|
/** Write a secrets file with the right permissions and no half-written state. */
|
|
451
553
|
function writeSecretFile(file, text) {
|
|
452
554
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
|
|
@@ -458,6 +560,97 @@ function writeSecretFile(file, text) {
|
|
|
458
560
|
fs.chmodSync(file, SECRET_FILE_MODE);
|
|
459
561
|
}
|
|
460
562
|
|
|
563
|
+
/**
|
|
564
|
+
* Store one foreign secret in `~/.aegiscode/secrets.env` — the counterpart of
|
|
565
|
+
* `setEnvValue`, for the file that one exists to keep out of.
|
|
566
|
+
*
|
|
567
|
+
* The guard is the mirror image of `setEnvValue`'s: that function refuses a
|
|
568
|
+
* foreign name so `.env` cannot re-acquire one, and this one refuses anything
|
|
569
|
+
* that is NOT a foreign name, so `secrets.env` cannot become a second place a
|
|
570
|
+
* host credential is written (and therefore a second place to look for one).
|
|
571
|
+
*
|
|
572
|
+
* Deliberately has no `apply` option and never touches any env object: a
|
|
573
|
+
* foreign secret's whole point is staying out of `process.env` until the one
|
|
574
|
+
* caller that needs it asks by name (`resolveForeignSecret`), right before use.
|
|
575
|
+
*
|
|
576
|
+
* @param {string} name one of FOREIGN_SECRET_NAMES (or a FOREIGN_SECRET_PREFIXES match)
|
|
577
|
+
* @param {string} value the secret. Never returned, never logged.
|
|
578
|
+
* @param {object} [o]
|
|
579
|
+
* @param {string} [o.dir] defaults to aegisHome()
|
|
580
|
+
* @param {string} [o.file] an explicit path, for tests
|
|
581
|
+
* @returns {{ok:boolean, file:string, name:string, changed:boolean,
|
|
582
|
+
* created:boolean, replaced:boolean, mode:number, tightened:boolean,
|
|
583
|
+
* error:string}}
|
|
584
|
+
*/
|
|
585
|
+
function setForeignSecret(name, value, o = {}) {
|
|
586
|
+
const file = o.file || secretEnvFileFor(o.dir);
|
|
587
|
+
const out = {
|
|
588
|
+
ok: false, file, name: String(name || ''), changed: false, created: false,
|
|
589
|
+
replaced: false, mode: 0, tightened: false, error: '',
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
if (!isWritableName(name)) {
|
|
593
|
+
out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
|
|
594
|
+
return out;
|
|
595
|
+
}
|
|
596
|
+
if (!isForeignSecret(name)) {
|
|
597
|
+
out.error = `refusing to write ${name} to ${SECRETS_FILE} — it is a host credential, not a `
|
|
598
|
+
+ `foreign secret; use setEnvValue (${ENV_FILE}) instead`;
|
|
599
|
+
return out;
|
|
600
|
+
}
|
|
601
|
+
const secret = String(value == null ? '' : value).trim();
|
|
602
|
+
if (!secret) {
|
|
603
|
+
out.error = `refusing to write an empty ${name}`;
|
|
604
|
+
return out;
|
|
605
|
+
}
|
|
606
|
+
if (/[\r\n]/.test(String(value))) {
|
|
607
|
+
out.error = `refusing to write ${name} — the value contains a line break`;
|
|
608
|
+
return out;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
let before = '';
|
|
612
|
+
let previousMode = 0;
|
|
613
|
+
out.created = true;
|
|
614
|
+
try {
|
|
615
|
+
before = fs.readFileSync(file, 'utf8');
|
|
616
|
+
out.created = false;
|
|
617
|
+
try {
|
|
618
|
+
previousMode = fs.statSync(file).mode & 0o777;
|
|
619
|
+
} catch { /* advisory */ }
|
|
620
|
+
} catch (e) {
|
|
621
|
+
if (e && e.code !== 'ENOENT') {
|
|
622
|
+
out.error = `could not read ${file}: ${e.code || e.message}`;
|
|
623
|
+
return out;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const aligned = String(before).replace(/\r\n/g, '\n');
|
|
628
|
+
if (!out.created && parseEnvText(aligned)[name] === secret) {
|
|
629
|
+
// Same value already stored: leave the file (its mtime, its mode) alone.
|
|
630
|
+
out.ok = true;
|
|
631
|
+
out.changed = false;
|
|
632
|
+
out.replaced = true;
|
|
633
|
+
out.mode = previousMode || SECRET_FILE_MODE;
|
|
634
|
+
return out;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const { text, replaced } = upsertEnvText(aligned, name, secret);
|
|
638
|
+
try {
|
|
639
|
+
writeSecretFile(file, text);
|
|
640
|
+
} catch (e) {
|
|
641
|
+
out.error = `could not write ${file}: ${e.code || e.message}`;
|
|
642
|
+
return out;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
out.ok = true;
|
|
646
|
+
out.changed = true;
|
|
647
|
+
out.replaced = replaced;
|
|
648
|
+
out.mode = SECRET_FILE_MODE;
|
|
649
|
+
out.tightened =
|
|
650
|
+
platform.hasPosixModes() && !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
|
|
651
|
+
return out;
|
|
652
|
+
}
|
|
653
|
+
|
|
461
654
|
/**
|
|
462
655
|
* Move every foreign secret out of `~/.aegiscode/.env` into `secrets.env`.
|
|
463
656
|
*
|
|
@@ -532,6 +725,31 @@ function splitForeignSecrets(o = {}) {
|
|
|
532
725
|
return out;
|
|
533
726
|
}
|
|
534
727
|
|
|
728
|
+
/**
|
|
729
|
+
* The shortest value that can be a real vendor credential.
|
|
730
|
+
*
|
|
731
|
+
* Not a shape check on any one vendor's format — deliberately. The vendors this
|
|
732
|
+
* file serves disagree about their prefixes (`sk-ant-api03-`, `sk-proj-`,
|
|
733
|
+
* `aegis_`, `gsk_`, a bare opaque string for a custom gateway), and a prefix
|
|
734
|
+
* allow-list here would refuse a valid key for a provider added tomorrow. What
|
|
735
|
+
* every one of them agrees on is the FLOOR: no vendor issues a credential that
|
|
736
|
+
* is a handful of characters. A value below this is not a key somebody typed
|
|
737
|
+
* wrongly-shaped, it is a paste that lost its payload or an answer typed into
|
|
738
|
+
* the wrong prompt, and the difference matters because the two failure modes
|
|
739
|
+
* look nothing alike to the user (see `providerKeyFromEnv`, and the upstream
|
|
740
|
+
* 401 that a 2-character value produced).
|
|
741
|
+
*
|
|
742
|
+
* Eight is the floor rather than something larger on purpose: it is below every
|
|
743
|
+
* real credential by orders of magnitude, so it can only ever reject values
|
|
744
|
+
* that are provably not keys, and it cannot reject one that is.
|
|
745
|
+
*/
|
|
746
|
+
const MIN_CREDENTIAL_LEN = 8;
|
|
747
|
+
|
|
748
|
+
/** Whether `value` is long enough to be a credential at all. See the floor above. */
|
|
749
|
+
function credentialLooksUsable(value) {
|
|
750
|
+
return typeof value === 'string' && value.trim().length >= MIN_CREDENTIAL_LEN;
|
|
751
|
+
}
|
|
752
|
+
|
|
535
753
|
/**
|
|
536
754
|
* The BYOK key for a provider out of the environment, if the env file (or the
|
|
537
755
|
* shell) supplies one. Returns '' when it does not — the encrypted store then
|
|
@@ -539,10 +757,27 @@ function splitForeignSecrets(o = {}) {
|
|
|
539
757
|
*/
|
|
540
758
|
function providerKeyFromEnv(providerId, env) {
|
|
541
759
|
const name = envVarFor(providerId);
|
|
542
|
-
if (!name) return { key: '', env: '' };
|
|
760
|
+
if (!name) return { key: '', env: '', rejected: null };
|
|
543
761
|
const raw = (env || process.env)[name];
|
|
544
762
|
const key = typeof raw === 'string' ? raw.trim() : '';
|
|
545
|
-
return { key, env: name };
|
|
763
|
+
if (key === '') return { key: '', env: name, rejected: null };
|
|
764
|
+
if (!credentialLooksUsable(key)) {
|
|
765
|
+
// A value that CANNOT be a vendor credential is not one, and returning it
|
|
766
|
+
// as `key` is how a junk entry became an upstream 401 instead of a prompt.
|
|
767
|
+
// Measured on this machine 2026-10-14: `~/.aegiscode/.env` held
|
|
768
|
+
// `ANTHROPIC_API_KEY=he` (2 characters — a paste that lost its value, or an
|
|
769
|
+
// answer typed into the wrong prompt). Every reader below took it as a key,
|
|
770
|
+
// the picker painted the `anthropic:*` rows as `configured`, the turn
|
|
771
|
+
// forwarded `X-Provider-Key: he` to the relay, and Anthropic answered
|
|
772
|
+
// `{"type":"error","error":{"type":"authentication_error","message":
|
|
773
|
+
// "Invalid bearer token"}}` — surfaced to the user as "Anthropic auth
|
|
774
|
+
// failed", which reads as "your Anthropic account is broken" when the
|
|
775
|
+
// truth is "this file holds two characters". Rejecting it here makes the
|
|
776
|
+
// row read as keyless, so `/model` prompts for the key again and the engine
|
|
777
|
+
// raises its own actionable "No key for …" instead of echoing a vendor 401.
|
|
778
|
+
return { key: '', env: name, rejected: `${name} holds ${key.length} character${key.length === 1 ? '' : 's'}, which cannot be a credential` };
|
|
779
|
+
}
|
|
780
|
+
return { key, env: name, rejected: null };
|
|
546
781
|
}
|
|
547
782
|
|
|
548
783
|
/** A variable name this module is willing to write. */
|
|
@@ -891,14 +1126,24 @@ function keyStatus(name, o = {}) {
|
|
|
891
1126
|
* pooled id (`deepseek`, `anthropic-haiku`, `nexus-brain`, …) is served by the
|
|
892
1127
|
* pool, which holds the provider keys itself, so the credential such a route
|
|
893
1128
|
* needs is the AEGIS ACCOUNT key — one variable, `AEGIS_API_KEY`, however many
|
|
894
|
-
* providers the picker lists.
|
|
1129
|
+
* providers the picker lists. The Claude Code Pro class is neither: it bills
|
|
1130
|
+
* nobody through AEGIS and reaches no vendor API, so the credential its route
|
|
1131
|
+
* needs is the subscription's own OAuth token — `foreign: true` marks that this
|
|
1132
|
+
* is a `secrets.env` name (`setForeignSecret`/`resolveForeignSecret`), not a
|
|
1133
|
+
* `.env` one (`setEnvValue`/`keyStatus`), so `modelKeyPlan`/`modelKeyQueue`/
|
|
1134
|
+
* `storeModelKey` in cli/src/models.js know which store to read and write.
|
|
895
1135
|
*
|
|
896
1136
|
* @param {string} modelId
|
|
897
|
-
* @param {string} [cls] 'byok' | 'aegis' | anything else
|
|
898
|
-
* @returns {{env:string, provider:string, vendor:string, pooled:boolean}}
|
|
1137
|
+
* @param {string} [cls] 'byok' | 'aegis' | 'pro' | anything else
|
|
1138
|
+
* @returns {{env:string, provider:string, vendor:string, pooled:boolean, foreign?:boolean}}
|
|
899
1139
|
*/
|
|
900
1140
|
function keyForModelId(modelId, cls) {
|
|
901
1141
|
const id = String(modelId == null ? '' : modelId).trim();
|
|
1142
|
+
if (String(cls || '').toLowerCase() === 'pro') {
|
|
1143
|
+
return {
|
|
1144
|
+
env: 'CLAUDE_CODE_OAUTH_TOKEN', provider: '', vendor: '', pooled: false, foreign: true,
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
902
1147
|
const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
|
|
903
1148
|
if (byok && id.includes(':')) {
|
|
904
1149
|
const provider = id.slice(0, id.indexOf(':')).trim();
|
|
@@ -996,6 +1241,11 @@ module.exports = {
|
|
|
996
1241
|
// (client/credentials.js) must be able to tell the two apart.
|
|
997
1242
|
isFromEnvFile,
|
|
998
1243
|
providerKeyFromEnv,
|
|
1244
|
+
// The floor a value must clear to be a credential at all, and the predicate
|
|
1245
|
+
// built on it — exported so a host can say WHY a row is keyless instead of
|
|
1246
|
+
// only that it is (see providerKeyFromEnv's `rejected`).
|
|
1247
|
+
MIN_CREDENTIAL_LEN,
|
|
1248
|
+
credentialLooksUsable,
|
|
999
1249
|
// The vendor half of "what key does this model id need": the account key is
|
|
1000
1250
|
// the route's credential, this is the provider key underneath it.
|
|
1001
1251
|
providerForModelId,
|
|
@@ -1017,5 +1267,9 @@ module.exports = {
|
|
|
1017
1267
|
secretEnvFileFor,
|
|
1018
1268
|
loadForeignSecrets,
|
|
1019
1269
|
foreignSecretValue,
|
|
1270
|
+
// The two the Claude Code Pro class reads/writes through — a value from
|
|
1271
|
+
// every place a user might have the token, and the one writer for the name.
|
|
1272
|
+
resolveForeignSecret,
|
|
1273
|
+
setForeignSecret,
|
|
1020
1274
|
splitForeignSecrets,
|
|
1021
1275
|
};
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
*
|
|
28
28
|
* ── what a user does now ───────────────────────────────────────────────────
|
|
29
29
|
*
|
|
30
|
-
* CLI `/model-add <provider> <model-id>` (and `/model-rm …`)
|
|
30
|
+
* CLI `/model-add <provider> [api-key] <model-id>` (and `/model-rm …`)
|
|
31
31
|
* Desktop Settings → "Add a model" → provider + id
|
|
32
32
|
* Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
|
|
33
33
|
*
|