aegiscode 7.0.6 → 7.0.8

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/src/models.js CHANGED
@@ -63,6 +63,32 @@ const { offerableCatalog } = require(resolveShared(path.join('client', 'brain-ca
63
63
  */
64
64
  const envFile = require(resolveShared(path.join('client', 'env-file.js')));
65
65
 
66
+ /**
67
+ * The Claude Code Pro transport, required the same way — so the 'pro' class's
68
+ * OWN foreign-secret check (below) can ask the same question `engine.js`'s
69
+ * `listModels('pro')` already answers for the row's `configured` flag:
70
+ * `claudeProStatus().loggedIn`, not only "is a token set aside in
71
+ * secrets.env". Without this, a machine signed in through the ordinary
72
+ * `claude login` flow (credentials.json, no `claude setup-token` ever run)
73
+ * reads as unconfigured here while the picker paints the same row
74
+ * `configured: true` — the picker says "ready", `/model` prompts for a token
75
+ * anyway.
76
+ */
77
+ const claudePro = require(resolveShared(path.join('desktop', 'lib', 'local', 'claude-pro.js')));
78
+
79
+ /** Whether this machine is already signed into Claude Code Pro/Max, any way
80
+ * `claudeProStatus` recognizes (credentials.json OAuth or API-key form, or
81
+ * `CLAUDE_CODE_OAUTH_TOKEN` already in the environment) — broader than the
82
+ * foreign-secret file alone, and the same check the picker's `configured`
83
+ * flag is built from. */
84
+ function claudeProLoggedIn() {
85
+ try {
86
+ return !!claudePro.claudeProStatus({ env: process.env }).loggedIn;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
66
92
  /** A pinned id of `null` means "no pin — let the pool choose" (the server's own default). */
67
93
  const NO_PIN = null;
68
94
 
@@ -236,6 +262,30 @@ function modelKeyPlan(entry, o = {}) {
236
262
  // for — an unanswerable prompt is worse than a turn that 400s with the id.
237
263
  return { needed: false, env: '', provider: '', pooled: plan.pooled, status: null, why: 'this id has no key variable' };
238
264
  }
265
+ if (plan.foreign) {
266
+ // Claude Code Pro: the credential lives in secrets.env (or an unmigrated
267
+ // .env line, or a real shell export), never in process.env at large — so
268
+ // `keyStatus` (which reads `.env`/process.env only) cannot answer this one;
269
+ // `resolveForeignSecret` is the function built to check every place it
270
+ // might actually be. See client/env-file.js keyForModelId.
271
+ //
272
+ // That alone is a narrower question than "is this machine signed in,
273
+ // though" — a plain `claude login` writes credentials.json and never
274
+ // touches secrets.env, so `claudeProLoggedIn()` is checked too; it is the
275
+ // same source `engine.js listModels('pro')` already paints the row's own
276
+ // `configured` flag from, so the two cannot disagree about one row.
277
+ const present = !!envFile.resolveForeignSecret(plan.env) || claudeProLoggedIn();
278
+ return {
279
+ needed: !present,
280
+ env: plan.env,
281
+ provider: '',
282
+ pooled: false,
283
+ status: { present, inFile: present, source: present ? 'file' : 'none' },
284
+ why: present
285
+ ? `${plan.env} is already set aside for Claude Code Pro`
286
+ : `no ${plan.env} is set aside for Claude Code Pro`,
287
+ };
288
+ }
239
289
  const status = envFile.keyStatus(plan.env);
240
290
  if (plan.pooled) {
241
291
  const needed = !status.present && !o.accountConfigured;
@@ -314,6 +364,27 @@ function modelKeyQueue(entry, o = {}) {
314
364
  // unanswerable prompt is worse than a turn that 400s with the id in it.
315
365
  if (!plan.env) return [];
316
366
 
367
+ if (plan.foreign) {
368
+ // Claude Code Pro bills nobody through AEGIS and calls no vendor API, so
369
+ // neither the account key nor a vendor key belongs in this queue — the
370
+ // ONE credential this route needs is the subscription's own OAuth token.
371
+ // There is no dedicated command for it (no `/byok-key` equivalent): it is
372
+ // asked for here, the same place every other row's key is asked for.
373
+ //
374
+ // `claudeProLoggedIn()` catches the plain `claude login` case the bare
375
+ // secrets.env check misses — see the matching note in `modelKeyPlan`.
376
+ if (envFile.resolveForeignSecret(plan.env) || claudeProLoggedIn()) return [];
377
+ return [{
378
+ env: plan.env,
379
+ provider: '',
380
+ vendor: '',
381
+ role: 'claude-pro',
382
+ needed: true,
383
+ status: { present: false },
384
+ why: `no ${plan.env} is set aside for Claude Code Pro`,
385
+ }];
386
+ }
387
+
317
388
  const steps = [];
318
389
  const account = envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);
319
390
  if (!account.present && !o.accountConfigured) {
@@ -384,14 +455,17 @@ function storeModelKey(entry, key, o = {}) {
384
455
  }
385
456
  const opts = { ...o };
386
457
  delete opts.env;
387
- const res = envFile.setEnvValue(env, key, opts);
458
+ // A foreign name (CLAUDE_CODE_OAUTH_TOKEN) goes to secrets.env, never .env —
459
+ // setEnvValue refuses it outright (client/env-file.js FOREIGN_SECRET_NAMES),
460
+ // and writing it there would be the exact ambient exposure the split ends.
461
+ const res = plan.foreign ? envFile.setForeignSecret(env, key, opts) : envFile.setEnvValue(env, key, opts);
388
462
  // `pooled` describes the VARIABLE that was written, not the class of the row:
389
463
  // the account key is the pooled route's credential wherever it is stored,
390
464
  // while a vendor key written for a pooled row is still the user's own vendor
391
465
  // key. Reading it off the row (as this once did) reported DEEPSEEK_API_KEY as
392
466
  // pooled, which told the caller the pool held a key the user had just supplied.
393
- const pooled = env === envFile.ACCOUNT_ENV_VAR;
394
- return { ...res, env, provider: env === plan.env ? plan.provider : '', pooled };
467
+ const pooled = !plan.foreign && env === envFile.ACCOUNT_ENV_VAR;
468
+ return { ...res, env, provider: env === plan.env ? plan.provider : '', pooled, foreign: !!plan.foreign };
395
469
  }
396
470
 
397
471
  /** The env var name a key for `entry` belongs in ('' when there is none). */
@@ -411,4 +485,5 @@ module.exports = {
411
485
  modelKeyQueue,
412
486
  storeModelKey,
413
487
  keyVarForModel,
488
+ claudeProLoggedIn,
414
489
  };
package/src/topup.js CHANGED
@@ -68,7 +68,7 @@ async function ensureKey(client, store) {
68
68
  const mod = loadShared('client/auto-provision.js');
69
69
  const provision = mod.autoProvisionApiKey || mod.default;
70
70
  if (typeof provision === 'function') {
71
- const res = await provision(client, store);
71
+ const res = await provision(client, store, { app: 'cli' });
72
72
  if (res && res.key && typeof client.setApiKey === 'function') client.setApiKey(res.key);
73
73
  }
74
74
  } catch {
@@ -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 boundedFetch(`${apiBase}${path}`, {
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 boundedFetch(`${apiBase}${path}`, {
783
+ const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, {
671
784
  method: 'GET',
672
785
  headers: headers || authHeaders(),
673
786
  signal: opts && opts.signal,
@@ -855,10 +968,11 @@ function createClient(opts = {}) {
855
968
  * zero balance. Re-registering an already-known fingerprint does NOT
856
969
  * re-grant it; the pool balance gate still applies once the allowance is
857
970
  * spent or the 30 days lapse. Sends no API key of its own — there isn't
858
- * one yet.
971
+ * one yet. `opts.app` names the host ('cli' | 'desktop' | 'mcp') so the
972
+ * server files this machine under its real name, not 'other'.
859
973
  */
860
974
  async function registerDevice(fingerprint, opts) {
861
- return apiPost('/api/v1/auth/register-device', { fingerprint }, undefined, opts);
975
+ return apiPost('/api/v1/auth/register-device', { fingerprint, app: opts && opts.app }, undefined, opts);
862
976
  }
863
977
 
864
978
  /** Build the OpenAI-style messages array from either a full history or the
@@ -1125,7 +1239,7 @@ function createClient(opts = {}) {
1125
1239
  // the gap the idle watchdog cannot reach — a server that accepts the
1126
1240
  // socket and never sends response headers, where `reader.read()` has not
1127
1241
  // been reached yet and so nothing is watching at all.
1128
- boundedFetch(`${apiBase}${path}`, {
1242
+ fetchWithRateLimitRetry(`${apiBase}${path}`, {
1129
1243
  method: 'POST',
1130
1244
  headers,
1131
1245
  body: JSON.stringify({ ...payload, stream: true }),
@@ -48,34 +48,75 @@ function provisionFailureText(result) {
48
48
  const err = result && result.error;
49
49
  if (!err) return 'the server returned no account key';
50
50
  if (err.status === 429) return 'too many sign-ups from this network — try again later';
51
+ if (err.status >= 500) return `aegiscloud.org failed to register this device: ${err.message}`;
51
52
  if (isTransientRegisterError(err)) return 'could not reach aegiscloud.org';
52
53
  return `the server refused the request (HTTP ${err.status})`;
53
54
  }
54
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
+
55
76
  /**
56
77
  * @param {object} aegisClient A client from client/aegis.js (createClient()).
57
78
  * @param {object} credentials client/credentials.js (or a compatible double).
58
- * @param {number[]} [retryDelaysMs] Wait before each retry of a transient failure.
59
- * @returns {Promise<{ok: boolean, key: string, error?: Error}>}
79
+ * @param {{app?: string, retryDelaysMs?: number[]}} [options] `app` names the host
80
+ * for the server's presence panel; `retryDelaysMs` waits before each retry of a
81
+ * transient failure.
82
+ * @returns {Promise<{ok: boolean, key: string, trialGranted?: boolean, reusedAccount?: boolean, error?: Error}>}
60
83
  * `ok` is true only when a usable key was obtained AND persisted to the
61
84
  * shared store; `aegisClient.setApiKey()` has already been called on
62
85
  * success, so the caller's client is immediately usable either way it
63
- * inspects `ok`.
86
+ * inspects `ok`. `trialGranted` is false when the server withheld the
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.
64
99
  */
65
- async function autoProvisionApiKey(aegisClient, credentials, retryDelaysMs = DEVICE_REGISTER_RETRY_DELAYS_MS) {
100
+ async function autoProvisionApiKey(aegisClient, credentials, options = {}) {
101
+ if (Array.isArray(options)) {
102
+ throw new TypeError('autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted');
103
+ }
66
104
  if (aegisClient.apiKey) return { ok: true, key: aegisClient.apiKey };
105
+ const { app, retryDelaysMs = DEVICE_REGISTER_RETRY_DELAYS_MS } = options;
67
106
  let lastError = null;
68
107
  for (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {
69
108
  if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, retryDelaysMs[attempt - 1]));
70
109
  const controller = new AbortController();
71
110
  const timer = setTimeout(() => controller.abort(), DEVICE_REGISTER_TIMEOUT_MS);
72
111
  try {
73
- const data = await aegisClient.registerDevice(machineFingerprint(), { signal: controller.signal });
112
+ const data = await aegisClient.registerDevice(machineFingerprint(), { app, signal: controller.signal });
74
113
  const key = data && typeof data.api_key === 'string' ? data.api_key.trim() : '';
75
114
  if (!key) return { ok: false, key: '' };
76
115
  const saved = credentials.saveApiKey(key);
77
116
  aegisClient.setApiKey(key);
78
- return { ok: !!saved.ok, key };
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 };
79
120
  } catch (err) {
80
121
  lastError = err;
81
122
  if (!isTransientRegisterError(err)) break;
@@ -86,4 +127,10 @@ async function autoProvisionApiKey(aegisClient, credentials, retryDelaysMs = DEV
86
127
  return { ok: false, key: '', error: lastError };
87
128
  }
88
129
 
89
- module.exports = { autoProvisionApiKey, provisionFailureText, DEVICE_REGISTER_TIMEOUT_MS, DEVICE_REGISTER_RETRY_DELAYS_MS };
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 — AEGIS keys are longer than that`,
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 };
@@ -111,8 +111,7 @@ function persistedInstallId() {
111
111
  * 4. `hostname:platform:arch` — last resort, kept only so this never throws.
112
112
  *
113
113
  * Only step 4 is guessable by a third party; steps 2 and 3 are both per-host
114
- * unique. `machineIdentityKind()` reports which one was used, so aegis1-side
115
- * abuse review can tell a genuine re-registration from a forged one.
114
+ * unique.
116
115
  *
117
116
  * @param {string} [overrideId] - test-only override for the raw machine identity.
118
117
  */
@@ -136,15 +135,9 @@ function machineIdentity(overrideId) {
136
135
  };
137
136
  }
138
137
 
139
- /** Which identity class the fingerprint on THIS host is derived from. */
140
- function machineIdentityKind() {
141
- return machineIdentity().kind;
142
- }
143
-
144
138
  module.exports = {
145
139
  machineFingerprint,
146
140
  machineIdentity,
147
- machineIdentityKind,
148
141
  readMachineId,
149
142
  persistedInstallId,
150
143
  };