aegisone 1.0.18 → 1.0.21

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 (61) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -1
  3. package/scripts/bump.mjs +29 -4
  4. package/scripts/predist.mjs +15 -2
  5. package/src/dispatch.js +1 -0
  6. package/vendor/cli/bin/aegiscode.js +41 -0
  7. package/vendor/cli/package.json +2 -1
  8. package/vendor/cli/scripts/predist.mjs +6 -3
  9. package/vendor/cli/src/app.js +436 -24
  10. package/vendor/cli/src/autonomous.js +19 -2
  11. package/vendor/cli/src/chatflow.js +77 -4
  12. package/vendor/cli/src/commands.js +220 -10
  13. package/vendor/cli/src/config.js +21 -0
  14. package/vendor/cli/src/connect.js +351 -0
  15. package/vendor/cli/src/deps.js +97 -1
  16. package/vendor/cli/src/engine.js +98 -8
  17. package/vendor/cli/src/fingerprint.js +46 -16
  18. package/vendor/cli/src/limits.js +1 -1
  19. package/vendor/cli/src/overlays.js +54 -0
  20. package/vendor/cli/src/provenance.lock.json +3 -3
  21. package/vendor/cli/src/screens.js +14 -1
  22. package/vendor/cli/src/update.js +103 -12
  23. package/vendor/cli/vendor/client/aegis.js +169 -3
  24. package/vendor/cli/vendor/client/credentials.js +9 -2
  25. package/vendor/cli/vendor/client/drive-connect.js +87 -0
  26. package/vendor/cli/vendor/client/drive-upload.js +176 -0
  27. package/vendor/cli/vendor/client/google-signin.js +127 -0
  28. package/vendor/cli/vendor/client/record-vault.js +431 -113
  29. package/vendor/cli/vendor/client/update.js +366 -8
  30. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +134 -11
  31. package/vendor/cli/vendor/desktop/lib/local/engine.js +111 -26
  32. package/vendor/cli/vendor/desktop/lib/local/prompt.js +67 -37
  33. package/vendor/cli/vendor/desktop/lib/local/tools.js +49 -13
  34. package/vendor/cli/vendor/desktop/lib/settings.js +65 -24
  35. package/vendor/desktop/lib/auto.js +11 -7
  36. package/vendor/desktop/lib/fingerprint.js +76 -17
  37. package/vendor/desktop/lib/google-connect.js +171 -0
  38. package/vendor/desktop/lib/local/claude-pro.js +134 -11
  39. package/vendor/desktop/lib/local/engine.js +111 -26
  40. package/vendor/desktop/lib/local/prompt.js +67 -37
  41. package/vendor/desktop/lib/local/tools.js +49 -13
  42. package/vendor/desktop/lib/settings.js +65 -24
  43. package/vendor/desktop/main.js +270 -36
  44. package/vendor/desktop/package.json +5 -2
  45. package/vendor/desktop/preload.js +45 -12
  46. package/vendor/desktop/renderer/app.js +691 -22
  47. package/vendor/desktop/renderer/budget.js +18 -9
  48. package/vendor/desktop/renderer/companion.js +225 -0
  49. package/vendor/desktop/renderer/fingerprint.css +16 -0
  50. package/vendor/desktop/renderer/fingerprint.js +136 -2
  51. package/vendor/desktop/renderer/index.html +302 -121
  52. package/vendor/desktop/renderer/provider-toolbar.js +136 -0
  53. package/vendor/desktop/renderer/providers.js +261 -0
  54. package/vendor/desktop/renderer/style.css +547 -171
  55. package/vendor/desktop/vendor/aegis.js +169 -3
  56. package/vendor/desktop/vendor/credentials.js +9 -2
  57. package/vendor/desktop/vendor/drive-connect.js +87 -0
  58. package/vendor/desktop/vendor/drive-upload.js +176 -0
  59. package/vendor/desktop/vendor/google-signin.js +127 -0
  60. package/vendor/desktop/vendor/record-vault.js +431 -113
  61. package/vendor/desktop/vendor/update.js +366 -8
@@ -140,8 +140,19 @@ Key:
140
140
  Vault:
141
141
  publish copies the SEALED BYTES to the vault, byte-identical, and
142
142
  writes the link (<record>.anchor.json) beside the local
143
- copy. Default target gdrive:AEGIS-AGPL (override with
144
- --remote/--root, or AEGIS_VAULT_REMOTE/ROOT).
143
+ copy.
144
+
145
+ DEFAULT BACKEND: aegiscloud — the account this machine
146
+ already registered for (the same device key every other
147
+ cloud feature uses, so publishing needs no second
148
+ sign-in). Nothing to configure; if there is no key yet,
149
+ 'aegiscode login' gives you one.
150
+
151
+ --backend rclone puts the copy somewhere YOU own instead:
152
+ --remote <name> --root <folder> (AEGIS_VAULT_REMOTE /
153
+ AEGIS_VAULT_ROOT), e.g. --remote gdrive --root
154
+ AEGIS-AGPL. That needs an rclone remote already
155
+ configured; the account vault does not.
145
156
  anchor re-downloads the published copy and checks three separate
146
157
  things: present, unchanged (sha256), still attested.
147
158
  vault --audit inspects every object already in the vault for key
@@ -370,7 +381,7 @@ function newestRecord(dataDir) {
370
381
  return files.length ? files[0].f : null;
371
382
  }
372
383
 
373
- function publish(argv, io) {
384
+ async function publish(argv, io) {
374
385
  const { authorship, vault } = load();
375
386
  const env = io.env || process.env;
376
387
  const positional = argv.find((a) => !a.startsWith('-'));
@@ -385,7 +396,7 @@ function publish(argv, io) {
385
396
  }
386
397
  if (!fs.existsSync(file)) throw new Error(`fingerprint: no record at ${file}`);
387
398
 
388
- const r = vault.publish({
399
+ const r = await vault.publish({
389
400
  file,
390
401
  argv,
391
402
  env,
@@ -401,6 +412,7 @@ function publish(argv, io) {
401
412
  io.stdout.write(
402
413
  [
403
414
  `dry run nothing uploaded`,
415
+ `backend ${r.backend}`,
404
416
  `record ${file}`,
405
417
  `would go ${r.remotePath}`,
406
418
  ...r.commands.map((c) => ` ${c}`),
@@ -410,10 +422,10 @@ function publish(argv, io) {
410
422
  }
411
423
  io.stdout.write(
412
424
  [
413
- `published ${r.remotePath}`,
425
+ `published ${r.remotePath} (${r.backend})`,
414
426
  `identity φ_${r.anchor.keyFingerprint}-${r.anchor.behaviour || 'unobserved'}`,
415
427
  `digest sha256 ${r.sha256.slice(0, 16)}… (${r.bytes} bytes, byte-identical to ${file})`,
416
- `link ${r.url || '(no Drive id returned — the copy is at the path above)'}`,
428
+ `link ${r.url || '(no share link — the copy is at the path above)'}`,
417
429
  `anchored ${r.localAnchor}${r.indexLines === null ? '' : ` · ledger lines ${r.indexLines}`}`,
418
430
  '',
419
431
  'The key was NOT published. Only the sealed record travels; verify the copy',
@@ -423,12 +435,12 @@ function publish(argv, io) {
423
435
  return 0;
424
436
  }
425
437
 
426
- function anchorCmd(argv, io) {
438
+ async function anchorCmd(argv, io) {
427
439
  const { vault } = load();
428
440
  const file = argv.find((a) => !a.startsWith('-'));
429
441
  if (!file) throw new Error('fingerprint: anchor needs a record file (the one you published)');
430
442
 
431
- const r = vault.checkAnchor({ file: path.resolve(file), argv, env: io.env || process.env });
443
+ const r = await vault.checkAnchor({ file: path.resolve(file), argv, env: io.env || process.env });
432
444
  if (io.json) {
433
445
  io.stdout.write(JSON.stringify(r, null, 2) + '\n');
434
446
  return r.ok ? 0 : 1;
@@ -452,13 +464,13 @@ function anchorCmd(argv, io) {
452
464
  return r.ok ? 0 : 1;
453
465
  }
454
466
 
455
- function vaultCmd(argv, io) {
467
+ async function vaultCmd(argv, io) {
456
468
  const { authorship, vault } = load();
457
469
  const env = io.env || process.env;
458
470
  const audit = has(argv, '--audit');
459
471
 
460
472
  if (audit) {
461
- const r = vault.audit({ argv, env, secret: secretOrNull(authorship, argv, env) });
473
+ const r = await vault.audit({ argv, env, secret: secretOrNull(authorship, argv, env) });
462
474
  if (io.json) {
463
475
  io.stdout.write(JSON.stringify(r, null, 2) + '\n');
464
476
  return r.ok ? 0 : 1;
@@ -469,7 +481,7 @@ function vaultCmd(argv, io) {
469
481
  }
470
482
  io.stdout.write(
471
483
  [
472
- `vault ${r.remote}:${r.root}`,
484
+ `vault ${r.where} (backend ${r.backend})`,
473
485
  `inspected ${r.checked} of ${r.files} object(s)`,
474
486
  r.uninspected.length ? `skipped ${r.uninspected.length} (see --json)` : '',
475
487
  '',
@@ -490,12 +502,12 @@ function vaultCmd(argv, io) {
490
502
  return r.ok ? 0 : 1;
491
503
  }
492
504
 
493
- const r = vault.list({ argv, env });
505
+ const r = await vault.list({ argv, env });
494
506
  if (io.json) {
495
507
  io.stdout.write(JSON.stringify(r, null, 2) + '\n');
496
508
  return 0;
497
509
  }
498
- const lines = [`vault ${r.remote}:${r.root} (${r.records.length} record(s))`];
510
+ const lines = [`vault ${r.where} (${r.records.length} record(s), backend ${r.backend})`];
499
511
  for (const rec of r.records) {
500
512
  lines.push(
501
513
  ` ${rec.name}`,
@@ -545,12 +557,18 @@ function runFingerprint(sub, argv = [], io = {}) {
545
557
  return verify(argv, out);
546
558
  case 'backup':
547
559
  return backup(argv, out);
560
+ // The three vault subcommands are async because the default vault is
561
+ // the account (an HTTP vault) as well as rclone. They keep the same
562
+ // contract though — an exit code, and a throw becomes exit 2 — so a
563
+ // caller only has to `await` the result; the sync subcommands above
564
+ // still return a plain number, which is what `runFingerprint` always did
565
+ // and what its tests assert.
548
566
  case 'publish':
549
- return publish(argv, out);
567
+ return asExitCode(publish(argv, out), out);
550
568
  case 'anchor':
551
- return anchorCmd(argv, out);
569
+ return asExitCode(anchorCmd(argv, out), out);
552
570
  case 'vault':
553
- return vaultCmd(argv, out);
571
+ return asExitCode(vaultCmd(argv, out), out);
554
572
  default:
555
573
  out.stderr.write(`aegiscode: unknown fingerprint subcommand "${sub}"\n\n${HELP}\n`);
556
574
  return 2;
@@ -561,4 +579,16 @@ function runFingerprint(sub, argv = [], io = {}) {
561
579
  }
562
580
  }
563
581
 
582
+ /**
583
+ * A vault subcommand's promise, as the same exit-code contract the sync
584
+ * subcommands have: a rejection is a usage-shaped line on stderr and exit 2,
585
+ * never a stack trace over a user's record (see this file's header on 1 vs 2).
586
+ */
587
+ function asExitCode(promise, io) {
588
+ return promise.catch((e) => {
589
+ io.stderr.write(`aegiscode: ${(e && e.message) || e}\n`);
590
+ return 2;
591
+ });
592
+ }
593
+
564
594
  module.exports = { runFingerprint, HELP, slug, defaultRecordPath, flag, everyFlag };
@@ -101,7 +101,7 @@ const UNITS = Object.freeze([
101
101
  * The masked digest of the sealed set. Rewritten ONLY by
102
102
  * `node tools/provenance.mjs seal --write`, never by hand.
103
103
  */
104
- const SEALED = '32ce3ebb806e116aefc6be2e3a8e6fbc04503cedf85e4460c78baf761c3b92c6';
104
+ const SEALED = '5125d89e9e3488b276cecb70e0107daa55c1c96424641b985fc7321c63518884';
105
105
 
106
106
  /** Subcommands that a build failing this check does not get to run. */
107
107
  const PRIVILEGED = Object.freeze(['gate', 'provenance', 'mcp']);
@@ -396,12 +396,66 @@ function ago(ts) {
396
396
  return `${Math.round(ms / 86_400_000)}d ago`;
397
397
  }
398
398
 
399
+ // ── BYOK provider picker overlay (/byok-set, /byok-key with no argument) ────
400
+
401
+ /**
402
+ * The picker `/byok-set <provider>` draws when no provider was typed.
403
+ *
404
+ * The provider id was the one thing this flow asked the user to RECALL: `/byok`
405
+ * listed ~20 ids, and storing a key meant reading one off that list and typing
406
+ * it back — retyped wrong, it either matched nothing ("unknown provider") or,
407
+ * worse, matched an alias of another vendor. The rows are the catalog's own,
408
+ * so the id Enter sends is the id the relay will be asked for.
409
+ *
410
+ * @param {Array} providers catalog rows ({id, label?, configured?, masked?})
411
+ * @param {number} sel selected index
412
+ * @param {number} width
413
+ * @param {string|null} [current] the provider already set on this machine, if
414
+ * any (marked, not selected — "set" is shown per row anyway)
415
+ * @param {string} [hint] the footer line; differs between `/byok-set` (the
416
+ * account-side store) and `/byok-key` (this machine's store)
417
+ */
418
+ function renderProviderPicker(providers, sel = 0, width = 80, current = null, hint = null) {
419
+ const list = Array.isArray(providers) ? providers : [];
420
+ const lines = [];
421
+ lines.push(blank(width));
422
+ lines.push([span('', ' '), span(C.white + BOLD, 'Select provider'), span(BOLD_OFF, '')]);
423
+ lines.push([span('', ' '), span(C.gray, 'Which vendor the key you are about to paste belongs to.')]);
424
+ lines.push(blank(width));
425
+ for (let i = 0; i < list.length; i++) {
426
+ const p = list[i] || {};
427
+ const id = String(p.id || '');
428
+ if (!id) continue;
429
+ const active = i === sel;
430
+ const cur = current != null && id === current;
431
+ const left = active ? span(C.lavender, GLYPH.cursor) : span('', ' ');
432
+ const nameSpan = active ? span(C.lavender, id) : span(C.white, id);
433
+ const mark = cur ? span(C.green, ' ' + GLYPH.check) : span('', '');
434
+ const name = String(p.label || '');
435
+ const pad = ' '.repeat(Math.max(1, 16 - [...id].length));
436
+ const state = p.configured
437
+ ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
438
+ : span(C.gray, 'not set');
439
+ lines.push([
440
+ span('', ' '), left, span('', ' '), nameSpan, mark,
441
+ span(C.gray, pad + (name ? `${name} · ` : '')), state,
442
+ ]);
443
+ }
444
+ lines.push(blank(width));
445
+ lines.push([
446
+ span('', ' '),
447
+ span(C.gray, hint || `↑↓ or tab move ${GLYPH.bullet} enter picks ${GLYPH.bullet} esc cancels`),
448
+ ]);
449
+ return fit(lines, width);
450
+ }
451
+
399
452
  module.exports = {
400
453
  boldMatched,
401
454
  renderPalette,
402
455
  renderModelPicker,
403
456
  renderEffortPicker,
404
457
  renderClassPicker,
458
+ renderProviderPicker,
405
459
  renderResumeList,
406
460
  EFFORT_LEVELS,
407
461
  EFFORT_VALUES,
@@ -24,13 +24,13 @@
24
24
  "license": "AGPL-3.0-or-later",
25
25
  "source": "https://github.com/aegisinfo/aegiscode-plugin",
26
26
  "units": {
27
- "p1": "6ab4d502c73d950c4c17afaaa5afc350475050a0bb45e883a8fdb8c71ca04757",
27
+ "p1": "14c0d9bed6de48582c23fecf7ab8b3126fc828554c383359317fcf7ee18a3f64",
28
28
  "p2": "d63d147de5455eea111d000b748d7eef9572a11a08d31f2471d5ff146701342c",
29
29
  "p3": "ff962ac8dbf42cecb2477e2f77bf5ec61f88aa1751b0d4e506bf030fbc5fc6c6",
30
30
  "p4": "2e8385c3a653a2af324050b4b92aeb9d142fc6765c91a13ccc928c5d4a2dbedb",
31
31
  "p5": "408d67f78f31f6d637a26d2852e0c809a260544e613afdc64b731401c0ba3801",
32
- "p6": "50da0fa70ab4210f5fd6358c174009e91f481870136075f623a8592b1f19bd90",
33
- "p7": "227117377da48ae003c4b971d242d579bfc8156c61d7719a2d3b331022a9b570",
32
+ "p6": "22bcd0b5dc1afad8d870652fbf1fd25bd0a547be9d8700161449cafa35bab6eb",
33
+ "p7": "81f2819d246a73c93307885cf09d8b7843e1dc1ce2bd6b4632869c00613422f6",
34
34
  "p8": "3cc054d06715e065fe635b37b7d1bb98bf7989d64453a572ddbb77cec5b830e7"
35
35
  }
36
36
  }
@@ -44,7 +44,7 @@ const { TAGLINE, TAGLINE_SHORT, welcomeArtParts } = require('./art.js');
44
44
  const { renderDiffPreview } = require('./markdown.js');
45
45
  const render = require('./render.js');
46
46
  const { updateConfig, configExists, loadConfig } = require('./config.js');
47
- const { updateNotice, updateLine } = require('./update.js');
47
+ const { updateNotice, updateLine, serverNotice, serverUpdateLine } = require('./update.js');
48
48
  const credentials = require('./credentials.js');
49
49
  const { signupUrl, signupDisplayUrl } = require('./signup.js');
50
50
  const { createSettingsStore, isReservedNamespace } = require('./deps.js');
@@ -392,6 +392,19 @@ function welcomeLines(ctx, cols, rows, firstRun = true) {
392
392
  save: (v) => { try { updateConfig({ updateCheck: v }); } catch { /* not fatal */ } },
393
393
  });
394
394
  updateMsg = updateLine({ current: VERSION, ...notice });
395
+
396
+ // The server's own verdict, which outranks the registry's: "a newer
397
+ // release exists" is a suggestion, "this build is no longer served" is
398
+ // the app about to stop working. aegis1 refuses clients below
399
+ // MIN_CLIENT_VERSION with a 426, so without this line a user learns it
400
+ // by being cut off mid-task instead of by reading their welcome box.
401
+ // Same cache-read-only rule: the refresh lands for the next launch.
402
+ const srv = serverNotice({
403
+ current: VERSION,
404
+ cache: cfg.updateCheckServer,
405
+ save: (v) => { try { updateConfig({ updateCheckServer: v }); } catch { /* not fatal */ } },
406
+ });
407
+ updateMsg = serverUpdateLine(srv) || updateMsg;
395
408
  } catch {
396
409
  // An update notice is never worth failing a launch over.
397
410
  }
@@ -13,9 +13,9 @@
13
13
  * checker. Resolved through deps.js so the in-repo and published-vendor
14
14
  * layouts both work.
15
15
  *
16
- * On top of the shared checker this module carries the three pieces /upgrade
17
- * needs — `compareVersions`, `upgradeAdvice` and `latestPublishedVersion` —
18
- * ported from the upstream engine reference. They belong
16
+ * On top of the shared checker this module carries the pieces /upgrade needs —
17
+ * `compareVersions`, `upgradeAdvice`, `latestPublishedVersion` and
18
+ * `installMethod` — ported from the upstream engine reference. They belong
19
19
  * here, next to `isNewer`/`updateLine`, so the CLI has ONE idea of "is there a
20
20
  * newer published version": the welcome-box notice and /upgrade now answer
21
21
  * from the same place and compare versions the same way. The shared module's
@@ -24,6 +24,8 @@
24
24
  * code, not a copy).
25
25
  */
26
26
 
27
+ const path = require('node:path');
28
+ const fs = require('node:fs');
27
29
  const { execFileSync } = require('node:child_process');
28
30
 
29
31
  const { resolveShared } = require('./deps.js');
@@ -34,6 +36,35 @@ const VERSION = require('../package.json').version;
34
36
  /** Both hosts publish from npm; the CLI is `aegiscode`. */
35
37
  const PKG = shared.PKG || 'aegiscode';
36
38
 
39
+ /**
40
+ * How THIS copy was installed: 'npm' | 'pip' | 'npx' | 'source'.
41
+ *
42
+ * Lazy on purpose — `detectInstallMethod` probes the filesystem, and the four
43
+ * call sites that only want a version string should not pay for it. Memoised
44
+ * because the answer cannot change while the process runs.
45
+ */
46
+ let methodCache = null;
47
+ function installMethod() {
48
+ if (methodCache) return methodCache;
49
+ const detect = shared.detectInstallMethod;
50
+ if (typeof detect !== 'function') { methodCache = 'npm'; return methodCache; }
51
+ try {
52
+ methodCache = detect({
53
+ env: process.env,
54
+ argv: process.argv,
55
+ pkg: PKG,
56
+ // The directory the running file lives in, and the package root above it
57
+ // (`cli/src` → `cli/`), which is what tells a checkout from a global
58
+ // install: `.git` exists in the repo, and in no published package.
59
+ entry: path.resolve(__dirname, '..'),
60
+ fileExists: (rel) => fs.existsSync(path.resolve(__dirname, '..', '..', rel)),
61
+ });
62
+ } catch {
63
+ methodCache = 'npm';
64
+ }
65
+ return methodCache;
66
+ }
67
+
37
68
  // ── /upgrade ─────────────────────────────────────────────────────────────────
38
69
 
39
70
  /** Compare two dotted version strings: -1 | 0 | 1 (prerelease tags ignored). */
@@ -48,7 +79,7 @@ function compareVersions(a, b) {
48
79
  }
49
80
 
50
81
  /** What /upgrade should say, given the local and published versions. */
51
- function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG } = {}) {
82
+ function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG, method = 'npm' } = {}) {
52
83
  if (!latest) {
53
84
  return {
54
85
  upToDate: null,
@@ -57,14 +88,22 @@ function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG } =
57
88
  }
58
89
  const cmp = compareVersions(latest, current);
59
90
  if (cmp > 0) {
60
- return {
61
- upToDate: false,
62
- lines: [
63
- ` Installed: ${current}`,
64
- ` Published: ${latest}`,
65
- ` Upgrade: npm i -g ${packageName}@latest`,
66
- ],
67
- };
91
+ // The command comes from the shared verdict, so /upgrade, the welcome box
92
+ // and the window's banner can never name three different installers — and
93
+ // so a pip install is not told to run npm (which would write a second copy
94
+ // beside the one it actually runs, and look like a no-op).
95
+ const plan = typeof shared.updatePlan === 'function'
96
+ ? shared.updatePlan({ current, latest, behind: true, channel: 'npm', pkg: packageName, method })
97
+ : null;
98
+ const instruction = (plan && plan.instruction) || `npm i -g ${packageName}@latest`;
99
+ const lines = [
100
+ ` Installed: ${current}`,
101
+ ` Published: ${latest}`,
102
+ ` Channel: ${method}`,
103
+ ` Upgrade: ${instruction}`,
104
+ ];
105
+ if (plan && plan.apply) lines.push(' (or run `/upgrade apply` to do it here)');
106
+ return { upToDate: false, lines, plan };
68
107
  }
69
108
  return {
70
109
  upToDate: true,
@@ -72,6 +111,56 @@ function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG } =
72
111
  };
73
112
  }
74
113
 
114
+ /**
115
+ * Actually run the upgrade, when the channel has a command to run.
116
+ *
117
+ * `/upgrade` used to print a command and stop there, which put the whole update
118
+ * behind "copy a shell line correctly" — and the window's banner had a button
119
+ * for the same thing. `apply: false` stays available because a source checkout
120
+ * and an npx run both have nothing for us to install.
121
+ *
122
+ * Never throws: a failing installer is a result, because a half-upgraded global
123
+ * package is exactly when a user needs to read the output rather than lose it
124
+ * to a traceback.
125
+ *
126
+ * @returns {{ok: boolean, skipped?: boolean, channel: string, command: ?string,
127
+ * output?: string, error?: string, instruction?: string}}
128
+ */
129
+ function applyUpgrade({ current = VERSION, packageName = PKG, method = 'npm', latest = null } = {}) {
130
+ const plan = typeof shared.updatePlan === 'function' && latest
131
+ ? shared.updatePlan({ current, latest, behind: true, channel: 'npm', pkg: packageName, method })
132
+ : null;
133
+ const target = plan && plan.apply ? plan.apply : null;
134
+ if (!target) {
135
+ const instruction = (plan && plan.instruction) || (method === 'npm'
136
+ ? `npm i -g ${packageName}@latest`
137
+ : 'restart to pick up the new version');
138
+ // Two different reasons to skip, and they are not interchangeable: a source
139
+ // checkout is the user's to pull, an npx run is already current by design.
140
+ return { ok: true, skipped: true, channel: method, command: null, instruction };
141
+ }
142
+ try {
143
+ const out = execFileSync(target.command, target.args, {
144
+ encoding: 'utf8',
145
+ timeout: 180_000,
146
+ stdio: ['ignore', 'pipe', 'pipe'],
147
+ });
148
+ return {
149
+ ok: true,
150
+ channel: method,
151
+ command: `${target.command} ${target.args.join(' ')}`,
152
+ output: String(out || '').trim(),
153
+ };
154
+ } catch (err) {
155
+ return {
156
+ ok: false,
157
+ channel: method,
158
+ command: `${target.command} ${target.args.join(' ')}`,
159
+ error: String((err && (err.stderr || err.message)) || err).trim(),
160
+ };
161
+ }
162
+ }
163
+
75
164
  /** Best-effort registry lookup (5s cap). Returns a version string or null. */
76
165
  function latestPublishedVersion({ packageName = PKG, timeoutMs = 5000 } = {}) {
77
166
  try {
@@ -88,5 +177,7 @@ module.exports = {
88
177
  VERSION,
89
178
  compareVersions,
90
179
  upgradeAdvice,
180
+ applyUpgrade,
181
+ installMethod,
91
182
  latestPublishedVersion,
92
183
  };
@@ -466,6 +466,29 @@ const RATE_LIMIT_MAX_WAIT_MS = 30000;
466
466
  /** Base for the exponential fallback when the server sends no `Retry-After`. */
467
467
  const RATE_LIMIT_BASE_WAIT_MS = 1000;
468
468
 
469
+ /**
470
+ * aegis1's chat-completions generator (`app.py` `nexus_chat_completions`'s
471
+ * `generate()`) wraps the whole upstream provider call in one `except
472
+ * Exception`, and on ANY failure forwards `str(e)` as a mid-stream SSE error
473
+ * frame: `{"error": {"message": str(e)[:200], "type": "server_error"}}`.
474
+ * Headers are already sent 200 OK by then, so there is no status code to
475
+ * tell a reset upstream socket apart from a real bug — both arrive as
476
+ * `postStream` throwing with `status: 200` and the CLI/desktop host showing
477
+ * `(backend error: [Errno 104] Connection reset by peer)` mid-turn.
478
+ *
479
+ * Narrowed to the Python exception messages a dropped TCP connection
480
+ * actually produces (ConnectionResetError/BrokenPipeError/ConnectionAbortedError
481
+ * and their usual Errno numbers), not every empty-turn error — a model that
482
+ * legitimately returned nothing must still fail on the first try, not retry
483
+ * forever. Only safe to retry when nothing streamed yet (`fullText` empty at
484
+ * the throw site below): no visible content can be duplicated by redoing the
485
+ * whole request from scratch.
486
+ */
487
+ const TRANSIENT_STREAM_ERROR_PATTERN =
488
+ /connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i;
489
+ const TRANSIENT_STREAM_RETRIES = 2;
490
+ const TRANSIENT_STREAM_BASE_WAIT_MS = 500;
491
+
469
492
  /**
470
493
  * .mcp.json / Electron pass config as "${VAR}" template refs. When the var is
471
494
  * unset, hosts have been observed to leave the template literally unexpanded
@@ -505,6 +528,78 @@ function createClient(opts = {}) {
505
528
  return value.split(apiKey).join('[redacted]');
506
529
  }
507
530
 
531
+ /**
532
+ * Transport failure codes → what actually happened, in words that point at
533
+ * the culprit. Names, not errno numbers, because "ECONNRESET" tells a user
534
+ * nothing while "the connection was reset mid-request" tells them to retry.
535
+ */
536
+ const AEGIS_NETWORK_ERROR_HINTS = {
537
+ ECONNRESET: 'connection reset by the backend',
538
+ ECONNREFUSED: 'connection refused — is the backend running?',
539
+ EPIPE: 'connection closed while sending the request',
540
+ ETIMEDOUT: 'connection timed out',
541
+ ENOTFOUND: 'host not found — check the endpoint URL',
542
+ EAI_AGAIN: 'DNS lookup failed temporarily',
543
+ EHOSTUNREACH: 'host unreachable',
544
+ ENETUNREACH: 'network unreachable',
545
+ CERT_HAS_EXPIRED: 'TLS certificate has expired',
546
+ DEPTH_ZERO_SELF_SIGNED_CERT: 'TLS certificate is self-signed',
547
+ UND_ERR_SOCKET: 'the socket closed before the response finished',
548
+ UND_ERR_CLOSED: 'the connection was closed',
549
+ UND_ERR_CONNECT_TIMEOUT: 'timed out connecting to the backend',
550
+ UND_ERR_HEADERS_TIMEOUT: 'the backend accepted the connection but never sent a response',
551
+ UND_ERR_BODY_TIMEOUT: 'the backend stalled mid-response',
552
+ UND_ERR_ABORTED: 'the request was aborted',
553
+ };
554
+
555
+ /**
556
+ * Turn a raw transport failure into something a person can act on.
557
+ *
558
+ * Node's undici raises `TypeError: fetch failed` for every socket-level
559
+ * fault and puts the real reason on `err.cause` (`ECONNRESET`,
560
+ * `UND_ERR_SOCKET`, `HeadersTimeoutError`, `ENOTFOUND`, …). Rethrown
561
+ * untouched, the user sees the literal string `fetch failed`, which names
562
+ * no component, no cause and no next step — and, worse, hides the fact that
563
+ * the backend is the thing that dropped us rather than a bad request.
564
+ *
565
+ * The cause code, when there is one, is the single most useful fact here,
566
+ * so it is promoted into `message` and kept on `cause`/`networkCode` for
567
+ * callers that want to branch on it. Everything else about the error is
568
+ * left alone.
569
+ */
570
+ function networkFailureError(err, base) {
571
+ const reraised = err instanceof Error ? err : new Error(String(err));
572
+ // The caller's own cancellation is not a failure and must stay untouched.
573
+ const name = reraised && reraised.name;
574
+ if (name === 'AbortError' || name === 'TimeoutError') return err;
575
+ const detail = describeNetworkCause(reraised);
576
+ const target = base || 'the backend';
577
+ const e = new Error(
578
+ detail
579
+ ? `Could not reach ${target} (${detail}).`
580
+ : `Could not reach ${target}: ${reraised.message || 'network failure'}.`
581
+ );
582
+ e.status = 0;
583
+ e.code = 'network';
584
+ e.networkCode = detail || null;
585
+ e.data = null;
586
+ e.cause = reraised;
587
+ return e;
588
+ }
589
+
590
+ /** The innermost human-meaningful reason from an undici error chain. */
591
+ function describeNetworkCause(err, depth = 0) {
592
+ if (!err || depth > 4) return null;
593
+ const code = err.code || (err.cause && err.cause.code);
594
+ const inner = err.cause;
595
+ const innerDetail = inner ? describeNetworkCause(inner, depth + 1) : null;
596
+ if (AEGIS_NETWORK_ERROR_HINTS[code]) return AEGIS_NETWORK_ERROR_HINTS[code];
597
+ if (innerDetail) return innerDetail;
598
+ // An undici cause often carries only a message ("other side closed").
599
+ if (inner && inner.message && inner.message !== err.message) return inner.message;
600
+ return code || null;
601
+ }
602
+
508
603
  /**
509
604
  * A bounded `fetch`: caller signal where there is one, an aborting timeout
510
605
  * where there is not. Returns the caller's abort untouched (so a host that
@@ -549,7 +644,7 @@ function createClient(opts = {}) {
549
644
  e.data = null;
550
645
  throw e;
551
646
  }
552
- throw err;
647
+ throw networkFailureError(err, apiBase);
553
648
  } finally {
554
649
  // The timeout is time-to-*headers* only, so it is cleared the moment the
555
650
  // response resolves: a long generation must never be cut off by it.
@@ -652,6 +747,30 @@ function createClient(opts = {}) {
652
747
  await sleep(wait, init && init.signal);
653
748
  res = await boundedFetch(url, init);
654
749
  }
750
+ // The NON-streaming twin of postStream's mid-stream transient retry below:
751
+ // aegis1's chat-completions route drains the same generate() generator
752
+ // itself when the caller sent `stream: false`, and on the SAME exception
753
+ // (a reset socket to the provider) returns it as a plain 503 —
754
+ // `{"error":{"message":"[Errno 104] Connection reset by peer","type":
755
+ // "server_error"}}` — not a 200 SSE frame, because no response has been
756
+ // sent yet on this branch. Peeked via a clone so a non-matching body (a
757
+ // real 503 — insufficient balance, "not configured" — is untouched for
758
+ // `parseResponse` to read and surface normally, unretried.
759
+ for (
760
+ let attempt = 0;
761
+ res && res.status >= 500 && res.status < 600 && attempt < TRANSIENT_STREAM_RETRIES;
762
+ attempt++
763
+ ) {
764
+ let text = '';
765
+ try {
766
+ text = await readCappedText(res.clone());
767
+ } catch {
768
+ break; // body already disturbed or unclonable — surface res as-is
769
+ }
770
+ if (!TRANSIENT_STREAM_ERROR_PATTERN.test(text)) break;
771
+ await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, attempt), init && init.signal);
772
+ res = await boundedFetch(url, init);
773
+ }
655
774
  return res;
656
775
  }
657
776
 
@@ -1066,7 +1185,14 @@ function createClient(opts = {}) {
1066
1185
  else if (mode) body.mode = mode;
1067
1186
  const headers = authHeaders(agentKey ? { 'X-AEGIS-Agent-Key': agentKey } : undefined);
1068
1187
  if (!stream || typeof onStream !== 'function') {
1069
- return decodeDsmlInResult(await apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers));
1188
+ // `signal` must be forwarded here. It was not, and the consequence was
1189
+ // silent: a caller that aborted a non-streaming turn saw the abort
1190
+ // ignored, the request ran on to its timeout, and the eventual error was
1191
+ // a timeout the user never asked for. postStream's own fallback at the
1192
+ // bottom of this function always forwarded it — only this branch did not.
1193
+ return decodeDsmlInResult(
1194
+ await apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers, { signal })
1195
+ );
1070
1196
  }
1071
1197
  // An OpenAI-compatible SSE response carries no `usage` unless the caller
1072
1198
  // asks for it (`stream_options.include_usage`). Without this the streamed
@@ -1237,7 +1363,10 @@ function createClient(opts = {}) {
1237
1363
  * This keeps streaming purely additive for hosts that opt in.
1238
1364
  */
1239
1365
  async function postStream(path, body, headers, onStream, signal, streamOpts) {
1240
- const { onReasoning, idleTimeoutMs, retryWithoutStreamOptions } = streamOpts || {};
1366
+ const {
1367
+ onReasoning, idleTimeoutMs, retryWithoutStreamOptions,
1368
+ _transientStreamAttempt: transientStreamAttempt = 0,
1369
+ } = streamOpts || {};
1241
1370
  const request = (payload) =>
1242
1371
  // `boundedFetch` here bounds time-to-*headers* only: fetch resolves when
1243
1372
  // the status line lands, and the timer is cleared in its `finally`, so a
@@ -1545,6 +1674,16 @@ function createClient(opts = {}) {
1545
1674
  }
1546
1675
 
1547
1676
  if (!fullText && sseError) {
1677
+ if (
1678
+ transientStreamAttempt < TRANSIENT_STREAM_RETRIES
1679
+ && TRANSIENT_STREAM_ERROR_PATTERN.test(sseError)
1680
+ ) {
1681
+ await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, transientStreamAttempt), signal);
1682
+ return postStream(path, body, headers, onStream, signal, {
1683
+ ...streamOpts,
1684
+ _transientStreamAttempt: transientStreamAttempt + 1,
1685
+ });
1686
+ }
1548
1687
  const err = new Error(sseError);
1549
1688
  err.status = res.status;
1550
1689
  throw err;
@@ -1763,6 +1902,32 @@ function createClient(opts = {}) {
1763
1902
  });
1764
1903
  }
1765
1904
 
1905
+ /**
1906
+ * aegis1's stored Google Drive connection for this account (`GET
1907
+ * /api/drive/token` — app.py's `get_drive_token`), authenticated with the
1908
+ * ordinary API key (the same header `authHeaders()` already sends, which
1909
+ * that route accepts alongside its session-cookie path). Resolves
1910
+ * `{connected, access_token, email}` — `connected: false` with no error
1911
+ * when this account has never run the browser's `/connect/drive` consent
1912
+ * screen (the route's 404: a real account, just nothing saved yet), since
1913
+ * "not yet connected" is the expected answer on every account until it
1914
+ * does. A 401 is a DIFFERENT fact — this key is not valid at all — so it is
1915
+ * left to throw rather than folded into the same "not connected" reading,
1916
+ * which would hide a real credential problem behind the normal first-run
1917
+ * state. The access token is refreshed server-side from the stored refresh
1918
+ * token on every call, so a caller never has to reason about expiry.
1919
+ */
1920
+ async function driveToken() {
1921
+ try {
1922
+ return await apiGet('/api/drive/token');
1923
+ } catch (e) {
1924
+ if (e && e.status === 404) {
1925
+ return { connected: false, access_token: null, email: null };
1926
+ }
1927
+ throw e;
1928
+ }
1929
+ }
1930
+
1766
1931
  return {
1767
1932
  apiBase,
1768
1933
  get apiKey() {
@@ -1798,6 +1963,7 @@ function createClient(opts = {}) {
1798
1963
  conversationSyncPush,
1799
1964
  conversationSyncPull,
1800
1965
  importConversation,
1966
+ driveToken,
1801
1967
  randomUUID,
1802
1968
  };
1803
1969
  }