aegisone 1.0.9 → 1.0.16

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 (39) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/scripts/predist.mjs +19 -0
  4. package/src/child.js +121 -2
  5. package/vendor/cli/package.json +3 -2
  6. package/vendor/cli/src/app.js +176 -13
  7. package/vendor/cli/src/chatflow.js +198 -38
  8. package/vendor/cli/src/commands.js +82 -4
  9. package/vendor/cli/src/deps.js +29 -2
  10. package/vendor/cli/src/engine.js +8 -1
  11. package/vendor/cli/src/keys.js +5 -0
  12. package/vendor/cli/src/models.js +78 -3
  13. package/vendor/cli/src/overlays.js +25 -7
  14. package/vendor/cli/src/screens.js +5 -0
  15. package/vendor/cli/src/sysdiag.js +5 -0
  16. package/vendor/cli/src/topup.js +1 -1
  17. package/vendor/cli/vendor/client/aegis.js +119 -5
  18. package/vendor/cli/vendor/client/auto-provision.js +89 -17
  19. package/vendor/cli/vendor/client/credentials.js +8 -2
  20. package/vendor/cli/vendor/client/device-fingerprint.js +1 -8
  21. package/vendor/cli/vendor/client/env-file.js +262 -8
  22. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +755 -0
  23. package/vendor/cli/vendor/desktop/lib/local/engine.js +329 -12
  24. package/vendor/cli/vendor/mcp/server.js +1 -1
  25. package/vendor/cli/vendor/one/src/child.js +287 -0
  26. package/vendor/cli/vendor/one/src/permissions.js +371 -0
  27. package/vendor/desktop/lib/account-key.js +60 -0
  28. package/vendor/desktop/lib/local/claude-pro.js +755 -0
  29. package/vendor/desktop/lib/local/engine.js +329 -12
  30. package/vendor/desktop/main.js +109 -33
  31. package/vendor/desktop/package.json +4 -3
  32. package/vendor/desktop/preload.js +8 -0
  33. package/vendor/desktop/renderer/app.js +50 -0
  34. package/vendor/desktop/renderer/index.html +11 -0
  35. package/vendor/desktop/vendor/aegis.js +119 -5
  36. package/vendor/desktop/vendor/auto-provision.js +89 -17
  37. package/vendor/desktop/vendor/credentials.js +8 -2
  38. package/vendor/desktop/vendor/device-fingerprint.js +1 -8
  39. package/vendor/desktop/vendor/env-file.js +262 -8
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegis-desktop",
3
3
  "productName": "AEGIS Desktop",
4
- "version": "1.0.1",
4
+ "version": "1.0.8",
5
5
  "description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -32,7 +32,7 @@
32
32
  "demo": "node scripts/record-demo-gif.mjs",
33
33
  "dist": "npm run predist && electron-builder",
34
34
  "dist:dir": "npm run predist && electron-builder --dir",
35
- "check": "node --check main.js && node --check preload.js && node --check renderer/app.js && node --check renderer/quick.js && node --check renderer/budget.js && node --check renderer/usage.js && node --check renderer/stream-policy.js && node --check renderer/transcript-view.js && node --check renderer/diff.js && node --check renderer/diffview.js && node --check renderer/markdown.js && node --check renderer/vendor/aegis-highlight.js && node --check scripts/predist.mjs && node --check scripts/generate-icon.mjs && node --check scripts/bundle-fonts.mjs && node --check lib/local/local.js && node --check lib/local/context.js && node --check lib/local/engine.js && node --check lib/local/session-rounds.js && node --check lib/local/tools.js && node --check lib/local/prompt.js && node --check lib/local/shell.js && node --check lib/local/agents.js && node --check lib/local/queue.js && node --check lib/local/autonomous.js && node --check lib/settings.js && node --check lib/sync/sessions.js && node --check lib/sync/memory-queue.js && node --check lib/window-state.js && node --check lib/deep-link.js && node --check lib/quick-launcher.js && node --check lib/avatar/tiers.js && node --check lib/avatar/xp.js && node --check lib/avatar/level.js && node --check lib/avatar/events.js && node --check lib/avatar/persona.js && node --check bin/aegis.js",
35
+ "check": "node --check main.js && node --check preload.js && node --check renderer/app.js && node --check renderer/quick.js && node --check renderer/budget.js && node --check renderer/usage.js && node --check renderer/stream-policy.js && node --check renderer/transcript-view.js && node --check renderer/diff.js && node --check renderer/diffview.js && node --check renderer/markdown.js && node --check renderer/vendor/aegis-highlight.js && node --check scripts/predist.mjs && node --check scripts/generate-icon.mjs && node --check scripts/bundle-fonts.mjs && node --check lib/local/local.js && node --check lib/local/context.js && node --check lib/local/engine.js && node --check lib/local/session-rounds.js && node --check lib/local/tools.js && node --check lib/local/prompt.js && node --check lib/local/shell.js && node --check lib/local/agents.js && node --check lib/local/queue.js && node --check lib/local/autonomous.js && node --check lib/account-key.js && node --check lib/settings.js && node --check lib/sync/sessions.js && node --check lib/sync/memory-queue.js && node --check lib/window-state.js && node --check lib/deep-link.js && node --check lib/quick-launcher.js && node --check lib/avatar/tiers.js && node --check lib/avatar/xp.js && node --check lib/avatar/level.js && node --check lib/avatar/events.js && node --check lib/avatar/persona.js && node --check bin/aegis.js",
36
36
  "test:shell": "node ../test/desktop-shell.mjs",
37
37
  "test:model": "node ../test/model-dispatch.mjs",
38
38
  "test:budget": "node ../test/budget.test.mjs",
@@ -55,7 +55,8 @@
55
55
  "test:avatar-events": "node test/avatar-events.test.mjs",
56
56
  "test:avatar-tiers": "node test/avatar-tiers.test.mjs",
57
57
  "test:avatar-persona": "node test/avatar-persona.test.mjs",
58
- "test:renderer-fonts": "node test/renderer-fonts.test.mjs"
58
+ "test:renderer-fonts": "node test/renderer-fonts.test.mjs",
59
+ "test:account-key": "node test/account-key.test.mjs"
59
60
  },
60
61
  "dependencies": {
61
62
  "electron-updater": "^6.8.9"
@@ -27,6 +27,7 @@ const AUTO_PREFIX = 'auto:';
27
27
  const QUEUE_PROGRESS_CHANNEL = `${QUEUE_PREFIX}progress`;
28
28
  const CHAT_DELTA_CHANNEL = `${IPC_PREFIX}chatDelta`;
29
29
  const UPDATE_STATUS_CHANNEL = `${IPC_PREFIX}updateStatus`;
30
+ const ACCOUNT_STATUS_CHANNEL = `${IPC_PREFIX}accountStatusChanged`;
30
31
  const MENU_NEW_CHAT_CHANNEL = `${IPC_PREFIX}menuNewChat`;
31
32
  const MENU_SEARCH_CHANNEL = `${IPC_PREFIX}menuSearch`;
32
33
  const MENU_EXPORT_MARKDOWN_CHANNEL = `${IPC_PREFIX}menuExportMarkdown`;
@@ -268,6 +269,13 @@ const api = {
268
269
  ipcRenderer.on(UPDATE_STATUS_CHANNEL, listener);
269
270
  return () => ipcRenderer.removeListener(UPDATE_STATUS_CHANNEL, listener);
270
271
  },
272
+ accountStatus: () => invoke('accountStatus'),
273
+ registerAccount: () => invoke('registerAccount'),
274
+ onAccountStatus: (onStatus) => {
275
+ const listener = (_event, state) => onStatus(state);
276
+ ipcRenderer.on(ACCOUNT_STATUS_CHANNEL, listener);
277
+ return () => ipcRenderer.removeListener(ACCOUNT_STATUS_CHANNEL, listener);
278
+ },
271
279
  // Native menu accelerators with no built-in Electron role (Cmd/Ctrl+N,
272
280
  // Cmd/Ctrl+K — see main.js buildAppMenu): main.js just pings the channel,
273
281
  // the renderer owns what "new chat" / "search" actually do.
@@ -73,6 +73,11 @@ const ELEMENT_IDS = {
73
73
  updateRestartBtn: 'update-restart-btn',
74
74
  updateRetryBtn: 'update-retry-btn',
75
75
  updateLaterBtn: 'update-later-btn',
76
+ accountBanner: 'account-banner',
77
+ accountBannerText: 'account-banner-text',
78
+ accountRetryBtn: 'account-retry-btn',
79
+ keysAccount: 'keys-account',
80
+ keysAccountRetry: 'keys-account-retry',
76
81
  connDot: 'conn-dot',
77
82
  connText: 'conn-text',
78
83
  app: 'st-app',
@@ -1140,6 +1145,35 @@ function renderUpdateBanner(state) {
1140
1145
  els.updateBanner.hidden = false;
1141
1146
  }
1142
1147
 
1148
+ /** Why the last account registration failed; null while the account is set up. */
1149
+ let accountFailureReason = null;
1150
+
1151
+ function renderAccountBanner(state) {
1152
+ accountFailureReason = state && state.status === 'no-key' ? state.reason : null;
1153
+ renderKeysPopup();
1154
+ if (!els.accountBanner) return;
1155
+ if (!accountFailureReason) {
1156
+ els.accountBanner.hidden = true;
1157
+ return;
1158
+ }
1159
+ els.accountBannerText.textContent = `No AEGIS account key on this machine: ${accountFailureReason}.`;
1160
+ els.accountBanner.hidden = false;
1161
+ }
1162
+
1163
+ /** Retry registration from either surface; a success re-reads status so the sheet and key rows update. */
1164
+ function retryAccountSetup(button) {
1165
+ button.disabled = true;
1166
+ aegis.registerAccount()
1167
+ .then((state) => {
1168
+ renderAccountBanner(state);
1169
+ if (!state) return refreshAfterKeyChange();
1170
+ })
1171
+ .catch((err) => renderAccountBanner({ status: 'no-key', reason: String((err && err.message) || err) }))
1172
+ .finally(() => {
1173
+ button.disabled = false;
1174
+ });
1175
+ }
1176
+
1143
1177
  async function loadAccountInfo() {
1144
1178
  try {
1145
1179
  const verify = await aegis.verifyApiKey();
@@ -2875,6 +2909,13 @@ function renderKeysPopup() {
2875
2909
  if (els.keysRowAegis) els.keysRowAegis.classList.toggle('set', aegisSet);
2876
2910
  if (els.keysRowByok) els.keysRowByok.classList.toggle('set', byokSet);
2877
2911
  if (els.keysCount) els.keysCount.textContent = `${(aegisSet ? 1 : 0) + (byokSet ? 1 : 0)} / 2`;
2912
+ if (els.keysAccount) {
2913
+ els.keysAccount.hidden = !accountFailureReason;
2914
+ els.keysAccount.textContent = accountFailureReason
2915
+ ? `The AEGIS account key could not be set up: ${accountFailureReason}.`
2916
+ : '';
2917
+ }
2918
+ if (els.keysAccountRetry) els.keysAccountRetry.hidden = !accountFailureReason;
2878
2919
  if (els.keysHint) {
2879
2920
  els.keysHint.textContent =
2880
2921
  aegisSet && byokSet
@@ -5703,6 +5744,15 @@ async function init() {
5703
5744
 
5704
5745
  // Auto-update banner: `?`-guarded like the memory inspector above, since
5705
5746
  // the markup is optional and a missing node must never crash boot.
5747
+ if (els.accountBanner && aegis.onAccountStatus) {
5748
+ aegis.onAccountStatus(renderAccountBanner);
5749
+ aegis.accountStatus().then(renderAccountBanner).catch((err) => console.warn('account status unavailable', err));
5750
+ els.accountRetryBtn.addEventListener('click', () => retryAccountSetup(els.accountRetryBtn));
5751
+ if (els.keysAccountRetry) {
5752
+ els.keysAccountRetry.addEventListener('click', () => retryAccountSetup(els.keysAccountRetry));
5753
+ }
5754
+ }
5755
+
5706
5756
  if (els.updateBanner && aegis.onUpdateStatus) {
5707
5757
  aegis.onUpdateStatus(renderUpdateBanner);
5708
5758
  aegis.updateStatus().then(renderUpdateBanner).catch(() => {});
@@ -48,6 +48,13 @@
48
48
  </div>
49
49
  </div>
50
50
 
51
+ <div class="update-banner account-banner" id="account-banner" role="alert" hidden>
52
+ <span id="account-banner-text"></span>
53
+ <div class="update-banner-actions">
54
+ <button type="button" id="account-retry-btn" class="ghost-btn">Retry account setup</button>
55
+ </div>
56
+ </div>
57
+
51
58
  <main>
52
59
  <aside class="side">
53
60
  <section class="card">
@@ -832,9 +839,13 @@
832
839
  </div>
833
840
  </div>
834
841
 
842
+ <p class="hint" id="keys-account" role="alert" hidden></p>
835
843
  <p class="hint" id="keys-hint"></p>
836
844
 
837
845
  <div class="keys-actions">
846
+ <button type="button" id="keys-account-retry" class="ghost-btn" hidden>
847
+ Retry account setup
848
+ </button>
838
849
  <a
839
850
  class="ghost-btn"
840
851
  id="keys-get"
@@ -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 }),
@@ -33,32 +33,104 @@
33
33
  const { machineFingerprint } = require('./device-fingerprint.js');
34
34
 
35
35
  const DEVICE_REGISTER_TIMEOUT_MS = 8000;
36
+ const DEVICE_REGISTER_RETRY_DELAYS_MS = [1000, 3000];
37
+
38
+ // Network failure, timeout (status 0), 408, or 5xx. A 4xx — including 429, the
39
+ // server's per-IP registration cap — is a refusal, and retrying it only spends
40
+ // more of that cap.
41
+ function isTransientRegisterError(err) {
42
+ const status = err && err.status;
43
+ return !status || status === 408 || status >= 500;
44
+ }
45
+
46
+ // Why automatic registration gave up, in words a host can show the user.
47
+ function provisionFailureText(result) {
48
+ const err = result && result.error;
49
+ if (!err) return 'the server returned no account key';
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}`;
52
+ if (isTransientRegisterError(err)) return 'could not reach aegiscloud.org';
53
+ return `the server refused the request (HTTP ${err.status})`;
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
+ }
36
75
 
37
76
  /**
38
77
  * @param {object} aegisClient A client from client/aegis.js (createClient()).
39
78
  * @param {object} credentials client/credentials.js (or a compatible double).
40
- * @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}>}
41
83
  * `ok` is true only when a usable key was obtained AND persisted to the
42
84
  * shared store; `aegisClient.setApiKey()` has already been called on
43
85
  * success, so the caller's client is immediately usable either way it
44
- * 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.
45
99
  */
46
- async function autoProvisionApiKey(aegisClient, credentials) {
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
+ }
47
104
  if (aegisClient.apiKey) return { ok: true, key: aegisClient.apiKey };
48
- const controller = new AbortController();
49
- const timer = setTimeout(() => controller.abort(), DEVICE_REGISTER_TIMEOUT_MS);
50
- try {
51
- const data = await aegisClient.registerDevice(machineFingerprint(), { signal: controller.signal });
52
- const key = data && typeof data.api_key === 'string' ? data.api_key.trim() : '';
53
- if (!key) return { ok: false, key: '' };
54
- const saved = credentials.saveApiKey(key);
55
- aegisClient.setApiKey(key);
56
- return { ok: !!saved.ok, key };
57
- } catch (err) {
58
- return { ok: false, key: '', error: err };
59
- } finally {
60
- clearTimeout(timer);
105
+ const { app, retryDelaysMs = DEVICE_REGISTER_RETRY_DELAYS_MS } = options;
106
+ let lastError = null;
107
+ for (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {
108
+ if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, retryDelaysMs[attempt - 1]));
109
+ const controller = new AbortController();
110
+ const timer = setTimeout(() => controller.abort(), DEVICE_REGISTER_TIMEOUT_MS);
111
+ try {
112
+ const data = await aegisClient.registerDevice(machineFingerprint(), { app, signal: controller.signal });
113
+ const key = data && typeof data.api_key === 'string' ? data.api_key.trim() : '';
114
+ if (!key) return { ok: false, key: '' };
115
+ const saved = credentials.saveApiKey(key);
116
+ aegisClient.setApiKey(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 };
120
+ } catch (err) {
121
+ lastError = err;
122
+ if (!isTransientRegisterError(err)) break;
123
+ } finally {
124
+ clearTimeout(timer);
125
+ }
61
126
  }
127
+ return { ok: false, key: '', error: lastError };
62
128
  }
63
129
 
64
- module.exports = { autoProvisionApiKey, DEVICE_REGISTER_TIMEOUT_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
  };