aegiscode 6.8.10 → 6.8.12

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.
@@ -0,0 +1,235 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The CLI's presence beacon — the `aegiscode` half of `client/presence.js`.
5
+ *
6
+ * `client/presence.js` owns the protocol (the route, the cadence the server
7
+ * asks for, the backoff ladder, the body allowlist). This file owns the three
8
+ * things only the CLI can know:
9
+ *
10
+ * - WHICH key. The credential store resolution (env → credentials.json →
11
+ * config.json) is the CLI's, not the shared transport's, and it is the same
12
+ * resolution every other CLI call uses. A host with no key does not beacon:
13
+ * `presence.js` returns an inert store rather than 401-looping, and this
14
+ * module simply reports that it is off.
15
+ * - WHICH build. `cli/package.json` at require time, so the panel shows the
16
+ * version the user actually installed rather than a constant that drifts
17
+ * from the release.
18
+ * - HOW BUSY. `autonomous: true` while `aegiscode autonomous` is draining a
19
+ * queue, and the pending depth at send time, so the panel can tell "an idle
20
+ * terminal is open" from "this machine is working through a queue".
21
+ *
22
+ * A module-level singleton, because a beacon is a process-wide fact and the
23
+ * lifecycle hooks that start and stop it are in `bin/aegiscode.js` — argument
24
+ * parsing and process lifecycle, which is not testable — while everything
25
+ * below is driven directly by `test/cli-presence.test.mjs`.
26
+ *
27
+ * Kill switch: `AEGIS_NO_PRESENCE=1` (or `0`/`false` for the settings-file
28
+ * equivalent is NOT read here — this host has no settings store). An operator
29
+ * debugging a network stack, or a CI runner that must make no outbound calls,
30
+ * gets to turn the beacon off without a code change.
31
+ */
32
+
33
+ const path = require('node:path');
34
+ const { resolveShared } = require('./sharedpaths.js');
35
+
36
+ /** `AEGIS_NO_PRESENCE` truthy ⇒ never beacon from this host. Anything else
37
+ * (unset, '', '0', 'false', 'no') leaves the beacon on: the default has to be
38
+ * "beacon", because a presence panel that is off unless someone remembers to
39
+ * switch it on is a panel with no rows in it. */
40
+ const KILL_ENV = 'AEGIS_NO_PRESENCE';
41
+
42
+ function presenceDisabled(env) {
43
+ try {
44
+ const raw = env && env[KILL_ENV];
45
+ if (raw == null || String(raw).trim() === '') return false;
46
+ return /^(1|true|on|yes)$/i.test(String(raw).trim());
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ /** Lazily required so `--help`, `--version` and `key status` stay instant and
53
+ * dependency-free: a beacon is for a *session*, not for a subcommand. */
54
+ function loadShared() {
55
+ const presence = require(resolveShared(path.join('client', 'presence.js')));
56
+ const fingerprint = require(resolveShared(path.join('client', 'device-fingerprint.js')));
57
+ return { presence, fingerprint };
58
+ }
59
+
60
+ /** The CLI's own build string. A missing/unreadable package.json is not a
61
+ * reason to skip the beacon: the fields are individually optional server-side. */
62
+ function cliVersion() {
63
+ try {
64
+ return require(path.join(__dirname, '..', 'package.json')).version || null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ let current = null;
71
+
72
+ /**
73
+ * Start (or restart) the CLI beacon. Idempotent by replacement: calling it
74
+ * twice stops the first store, so the timer count cannot grow with the number
75
+ * of calls. Never throws — a beacon that cannot start is a beacon that is off,
76
+ * and the session proceeds.
77
+ *
78
+ * @param {object} [opts]
79
+ * @param {object} [opts.client] an already-built aegis client (its apiKey wins)
80
+ * @param {object} [opts.credentials] the credential store to resolve a key from
81
+ * @param {boolean} [opts.autonomous] this process is draining a queue
82
+ * @param {number|function} [opts.queueDepth] pending tasks, or a reader for them
83
+ * @param {object} [opts.env] override process.env (tests)
84
+ * @param {object} [opts.io] { stdout, stderr } — never used today, kept
85
+ * so a future `--verbose` can narrate a beat
86
+ * @returns {{enabled: boolean, reason: string|null, stop: () => void, state: () => object}}
87
+ */
88
+ function start(opts = {}) {
89
+ stop();
90
+ const env = opts.env || process.env;
91
+ if (presenceDisabled(env)) {
92
+ return (current = inert('kill-switch'));
93
+ }
94
+
95
+ let apiKey = '';
96
+ try {
97
+ if (opts.client && typeof opts.client.apiKey === 'string') apiKey = opts.client.apiKey;
98
+ if (!apiKey && opts.credentials && typeof opts.credentials.resolveApiKey === 'function') {
99
+ const resolved = opts.credentials.resolveApiKey({ env });
100
+ apiKey = (resolved && (resolved.key || resolved.apiKey)) || '';
101
+ }
102
+ } catch {
103
+ apiKey = '';
104
+ }
105
+ if (!apiKey) return (current = inert('no-api-key'));
106
+
107
+ try {
108
+ const { presence, fingerprint } = loadShared();
109
+ const store = presence.createPresence({
110
+ apiKey,
111
+ // 'cli', not 'aegiscode': aegis1 keeps only the names in its own
112
+ // PRESENCE_APPS tuple (app.py) and stores anything else as 'other', so a
113
+ // product name here would make every terminal session unidentifiable in
114
+ // the admin panel while still answering 200. See
115
+ // client/presence-constants.js — a test parses the server's tuple and
116
+ // fails if the two lists drift.
117
+ app: 'cli',
118
+ version: cliVersion(),
119
+ platform: process.platform,
120
+ // The SAME identity the device-registration path uses — see the header of
121
+ // client/presence.js for why the beacon must carry the machine, not a
122
+ // per-run random token. Computed here rather than inside presence.js so a
123
+ // fingerprint failure is visible at the call site.
124
+ install: fingerprint.machineFingerprint(),
125
+ queueDepth: opts.queueDepth,
126
+ autonomous: Boolean(opts.autonomous),
127
+ log: opts.log,
128
+ fetchImpl: opts.fetchImpl,
129
+ now: opts.now,
130
+ setTimer: opts.setTimer,
131
+ clearTimer: opts.clearTimer,
132
+ });
133
+ store.start();
134
+ return (current = store);
135
+ } catch (err) {
136
+ // A require failure here is a packaging bug, not a user-facing one: stay
137
+ // quiet, keep the session working, and leave `state().reason` for a test.
138
+ return (current = inert(`load-failed:${String((err && err.message) || err).slice(0, 80)}`));
139
+ }
140
+ }
141
+
142
+ function inert(reason) {
143
+ return {
144
+ enabled: false,
145
+ reason,
146
+ install: null,
147
+ stop: () => true,
148
+ state: () => ({ enabled: false, reason, beats: 0, failures: 0, running: false }),
149
+ };
150
+ }
151
+
152
+ /** Stop the beacon. Idempotent; safe when `start()` never ran. */
153
+ function stop() {
154
+ if (!current) return false;
155
+ try {
156
+ current.stop();
157
+ } catch {
158
+ /* an already-dead beacon is not an error */
159
+ }
160
+ current = null;
161
+ return true;
162
+ }
163
+
164
+ /** The active store (or null). For tests and for a host that wants to read
165
+ * `state()` — `{beats, failures, lastSeenAt, intervalMs}` — after a beat. */
166
+ function active() {
167
+ return current;
168
+ }
169
+
170
+ /**
171
+ * How many tasks are waiting, read at SEND time.
172
+ *
173
+ * Resolved through the shared-path resolver (`sharedpaths.js`) rather than by
174
+ * re-implementing a queue counter, so there is exactly one queue file and one
175
+ * definition of "pending" in this repo — the same `desktop/lib/local/queue.js`
176
+ * the desktop drains. A missing module, an unreadable file or a malformed line
177
+ * is 0: the beacon reports presence, not bookkeeping, and a broken queue must
178
+ * not silence the beacon that would have shown the machine was alive.
179
+ */
180
+ function queueDepthReader() {
181
+ let queue = null;
182
+ try {
183
+ queue = require(resolveShared(path.join('desktop', 'lib', 'local', 'queue.js')));
184
+ } catch {
185
+ queue = null;
186
+ }
187
+ return () => {
188
+ try {
189
+ if (!queue || typeof queue.readQueue !== 'function' || typeof queue.queuePath !== 'function') return 0;
190
+ const items = queue.readQueue(queue.queuePath());
191
+ return (Array.isArray(items) ? items : []).filter((t) => t && t.status === 'pending').length;
192
+ } catch {
193
+ return 0;
194
+ }
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Let an in-flight beat finish before the process exits.
200
+ *
201
+ * This is not optional politeness — it is the difference between a beat and no
202
+ * beat. `bin/aegiscode.js` ends with `process.exit()`, and a one-shot run
203
+ * (`aegiscode -p "…"`, `aegiscode autonomous run`) reaches it in tens of
204
+ * milliseconds, so the first beat posted at startup would be killed mid-flight
205
+ * and the machine would never appear in the panel. Bounded, because a beacon
206
+ * must never be the reason a CLI hangs: if the request has not answered within
207
+ * `timeoutMs`, the process exits and that beat is simply lost.
208
+ *
209
+ * @param {number} [timeoutMs] default 1500 — the beacon's own request timeout
210
+ * is 20 s, far too long to hold an exit open.
211
+ * @returns {Promise<'drained'|'none'|'timeout'>}
212
+ */
213
+ function flush(timeoutMs = 1500) {
214
+ try {
215
+ if (!current || typeof current.pending !== 'function') return Promise.resolve('none');
216
+ const inflight = current.pending();
217
+ if (!inflight) return Promise.resolve('none');
218
+ const limit = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0 ? Number(timeoutMs) : 1500;
219
+ return Promise.race([
220
+ Promise.resolve(inflight).then(() => 'drained', () => 'drained'),
221
+ new Promise((resolve) => {
222
+ // Deliberately NOT unref'd, unlike every other timer in this module: the
223
+ // caller is already in its exit path and has asked for a bounded wait, so
224
+ // this timer is the thing that must be allowed to keep the loop alive
225
+ // long enough to fire. An unref'd timer here would leave the process with
226
+ // an empty event loop and a `flush()` promise that never settles.
227
+ setTimeout(() => resolve('timeout'), limit);
228
+ }),
229
+ ]);
230
+ } catch {
231
+ return Promise.resolve('none');
232
+ }
233
+ }
234
+
235
+ module.exports = { start, stop, active, flush, presenceDisabled, queueDepthReader, cliVersion, KILL_ENV };
package/src/screens.js CHANGED
@@ -31,7 +31,7 @@
31
31
  const { getSize, paint, span, lineWidth, clip, w } = require('./screen.js');
32
32
  const events = require('./events.js');
33
33
  const { nextKey, KEY } = events;
34
- const { C, BOLD, BOLD_OFF, GLYPH, THEME_TABLE, themeOf } = require('./theme.js');
34
+ const { C, BOLD, BOLD_OFF, GLYPH, THEME_TABLE, themeOf, themeIsLight, terminalIsLight } = require('./theme.js');
35
35
  const { TAGLINE, TAGLINE_SHORT, welcomeArtParts } = require('./art.js');
36
36
  const { renderDiffPreview } = require('./markdown.js');
37
37
  const render = require('./render.js');
@@ -217,11 +217,14 @@ async function showTrustCheck(ctx) {
217
217
  // ── theme picker ─────────────────────────────────────────────────────────────
218
218
 
219
219
  /** Apply a picker row to a context: both the row index and the light flag, the
220
- * way the reference commits (`ctx.light = sel === 2 || sel === 4 || sel === 6`). */
220
+ * way the reference commits (`ctx.light = sel === 2 || sel === 4 || sel === 6`).
221
+ * Row 0 is "Auto (match terminal)", whose flag is resolved from the terminal's
222
+ * reported background by `themeIsLight` — reading the row's own `light` field
223
+ * would commit the dark fallback and make the one auto row a dark row. */
221
224
  function applyTheme(ctx, sel) {
222
225
  const row = THEME_TABLE[sel] || THEME_TABLE[1];
223
226
  ctx.themeIndex = sel;
224
- ctx.light = row.light;
227
+ ctx.light = themeIsLight(sel);
225
228
  return sel;
226
229
  }
227
230
 
@@ -262,7 +265,11 @@ function themePickerLines(ctx, cols, rows, sel) {
262
265
  */
263
266
  async function showThemePicker(ctx, title = `Welcome to ${PRODUCT}`) {
264
267
  const { cols, rows } = getSize();
265
- let sel = typeof ctx.themeIndex === 'number' ? ctx.themeIndex : 1;
268
+ // The highlighted row is a proposal about *this* terminal, so a first run
269
+ // proposes the one it can show: a light terminal opened on "Dark mode" is the
270
+ // same white-on-white mistake one keystroke away, this time as a default the
271
+ // user is asked to accept. Nothing is committed until they answer.
272
+ let sel = typeof ctx.themeIndex === 'number' ? ctx.themeIndex : terminalIsLight() ? 2 : 1;
266
273
  const renderScreen = () => paint(themePickerLines(ctx, cols, rows, sel));
267
274
  renderScreen();
268
275
  for (;;) {
package/src/theme.js CHANGED
@@ -221,8 +221,14 @@ const THEMES = { dark: C, light: LIGHT };
221
221
  * The theme picker's table, copied from the upstream engine's screens THEMES
222
222
  * (names and notes verbatim). `light` is the flag the reference sets on commit
223
223
  * (`ctx.light = sel === 2 || sel === 4 || sel === 6`); `palette` is what this
224
- * client resolves the row to, since it has no terminal-background probe and so
225
- * resolves "Auto" to the dark palette.
224
+ * client resolves the row to.
225
+ *
226
+ * Row 0 carries the reference's own note — "(match terminal)" — and now does
227
+ * what it says: `terminalIsLight()` reads the background the terminal reports
228
+ * about itself (`caps().background`, from `COLORFGBG`/`TERM_BACKGROUND`, see
229
+ * `caps.js`) and resolves the row to `LIGHT` or `C` accordingly. Its `light`
230
+ * field is therefore the *fallback* used when nothing is reported, not the
231
+ * answer; `themeIsLight()` is the function that decides.
226
232
  */
227
233
  const THEME_TABLE = [
228
234
  { name: 'Auto', note: '(match terminal)', light: false, palette: C },
@@ -234,6 +240,105 @@ const THEME_TABLE = [
234
240
  { name: 'Light mode', note: '(ANSI colors only)', light: true, palette: ANSI_LIGHT },
235
241
  ];
236
242
 
243
+ /** The picker row that means "match terminal" rather than "be dark/light". */
244
+ const AUTO_THEME_INDEX = 0;
245
+
246
+ /**
247
+ * True when the terminal's own background is light.
248
+ *
249
+ * The dark palette's primary text is `RGB(255,255,255)`: drawn over a light
250
+ * terminal it is white-on-white, which is a blank screen rather than a
251
+ * mis-styled one. So this is the one probe that decides between two *legible*
252
+ * palettes — it never changes the mark, the glyph set, the colour depth or the
253
+ * control sequences, and it is never inferred from `process.platform`.
254
+ *
255
+ * @param {object} [c] a caps object; defaults to the live process's
256
+ */
257
+ function terminalIsLight(c = caps()) {
258
+ return c.background === 'light';
259
+ }
260
+
261
+ /**
262
+ * Resolve a picker row to the palette family it should draw with — the single
263
+ * place "is this row light?" is answered, so a ctx whose `light` flag was
264
+ * seeded from the row index can never disagree with the palette `themeOf` picks.
265
+ *
266
+ * Explicit rows answer from their own flag; row 0 (Auto) asks the terminal; an
267
+ * index outside the table falls back to dark, which is what `themeOf` did with
268
+ * an unknown index before this existed.
269
+ *
270
+ * @param {number} themeIndex a row index from THEME_TABLE
271
+ * @param {object} [c] a caps object; defaults to the live process's
272
+ */
273
+ function themeIsLight(themeIndex, c = caps()) {
274
+ const row = THEME_TABLE[themeIndex];
275
+ if (!row) return false;
276
+ if (themeIndex === AUTO_THEME_INDEX) return terminalIsLight(c);
277
+ return !!row.light;
278
+ }
279
+
280
+ /**
281
+ * The sibling row: the same palette family at the other brightness.
282
+ *
283
+ * Row 0 (Auto) has no sibling — it is not a brightness, it is a question. The
284
+ * pairs are the picker's own (`Dark mode`/`Light mode`, and the colorblind and
285
+ * ANSI families likewise), so a blind choice of "colorblind-friendly" survives
286
+ * a correction and only its brightness changes.
287
+ */
288
+ const SIBLING_THEME_INDEX = [0, 2, 1, 4, 3, 6, 5];
289
+
290
+ /** True when a picker row's brightness is the opposite of the terminal's. */
291
+ function themeContradicts(themeIndex, c = caps()) {
292
+ const row = THEME_TABLE[themeIndex];
293
+ if (!row || themeIndex === AUTO_THEME_INDEX) return false;
294
+ // Without a report there is nothing to contradict. `background` is then the
295
+ // dark default and the stored row stands: overriding a preference on the
296
+ // strength of a *default* would be the same class of bug as reading a
297
+ // guessed background as if it were evidence.
298
+ if (!c || !c.backgroundKnown) return false;
299
+ return !!row.light !== (c.background === 'light');
300
+ }
301
+
302
+ /**
303
+ * A stored (or just-picked) theme row, corrected when the terminal it will be
304
+ * drawn on cannot show it.
305
+ *
306
+ * This is the other half of `themeIsLight`. That function answers "is row 0
307
+ * light?" — but rows 2, 4 and 6 are *explicitly* light, and an explicit row
308
+ * whose text cannot be read is not a preference. The recorded bug: a terminal
309
+ * background of `#1e1e2e` with `themeIndex: 2` in the config drew the light
310
+ * palette's primary text `RGB(40,40,40)` over it — a 1.11:1 contrast ratio,
311
+ * i.e. a body of text that is present and unreadable. The stored row had been
312
+ * chosen on a light terminal and outlived it, and nothing ever checked it
313
+ * against the terminal that was actually on screen.
314
+ *
315
+ * The correction keeps the user's family and flips only the brightness, so
316
+ * "colorblind-friendly" or "ANSI colors only" survives: the answer is the same
317
+ * palette at the brightness this terminal can display. `changed` is reported
318
+ * rather than acted on silently — a preference that was overridden is something
319
+ * the user is told about, and the stored value is left alone, so moving back to
320
+ * a light terminal restores the original choice by itself.
321
+ *
322
+ * @param {number} themeIndex the stored/selected row
323
+ * @param {object} [c] a caps object; defaults to the live process's
324
+ * @returns {{index: number, changed: boolean, reason: string, from: object|null}}
325
+ */
326
+ function reconcileThemeIndex(themeIndex, c = caps()) {
327
+ const row = THEME_TABLE[themeIndex];
328
+ if (!themeContradicts(themeIndex, c)) return { index: themeIndex, changed: false, reason: '', from: row || null };
329
+ const index = SIBLING_THEME_INDEX[themeIndex];
330
+ const to = THEME_TABLE[index];
331
+ const label = (r) => `${r.name}${r.note ? ' ' + r.note : ''}`;
332
+ return {
333
+ index,
334
+ changed: true,
335
+ from: row,
336
+ reason:
337
+ `saved theme "${label(row)}" is unreadable on this ${c.background} terminal ` +
338
+ `(${c.reasons.background}) — using "${label(to)}" instead`,
339
+ };
340
+ }
341
+
237
342
  /** The palette object for a theme-picker row index (out-of-range → dark). */
238
343
  function themeForIndex(i) {
239
344
  const row = THEME_TABLE[i];
@@ -246,9 +351,11 @@ function themeForIndex(i) {
246
351
  *
247
352
  * The light flag alone decides for the three default-brightness rows (indices
248
353
  * 0–2), which keeps `themeOf({light:true}) === LIGHT` and `themeOf({}) === C`
249
- * exactly as before. The colourblind and ANSI families are only consulted when
250
- * `themeIndex` actually names one of them (3–6), so an app that seeds
251
- * `themeIndex` to 0/1 for light/dark is unaffected.
354
+ * exactly as before — except for row 0, which is "Auto (match terminal)" and so
355
+ * asks the terminal instead of assuming dark. The colourblind and ANSI families
356
+ * are only consulted when `themeIndex` actually names one of them (3–6), so an
357
+ * app that seeds `themeIndex` to 0/1 for light/dark is unaffected (it is not
358
+ * seeding 0 unless it means Auto).
252
359
  *
253
360
  * The *depth* is deliberately not consulted here: `C` is already built from
254
361
  * `RGB()`, which is depth-aware, so a 16-colour console gets a 16-colour dark
@@ -260,6 +367,11 @@ function themeOf(ctx) {
260
367
  if (ctx && typeof ctx.themeIndex === 'number' && ctx.themeIndex >= 3 && ctx.themeIndex <= 6) {
261
368
  return themeForIndex(ctx.themeIndex);
262
369
  }
370
+ // Row 0 is "Auto (match terminal)": the terminal's own background decides,
371
+ // not a hardcoded dark. Without this branch the one row whose job is to match
372
+ // the terminal was the one row that could not, and a light terminal drew the
373
+ // dark palette's `RGB(255,255,255)` body text over its own white background.
374
+ if (ctx && ctx.themeIndex === AUTO_THEME_INDEX) return terminalIsLight() ? LIGHT : C;
263
375
  return ctx && ctx.light ? LIGHT : C;
264
376
  }
265
377
 
@@ -273,7 +385,9 @@ function themeOf(ctx) {
273
385
  function diffOf(ctx) {
274
386
  const light = ctx && typeof ctx.themeIndex === 'number' && ctx.themeIndex >= 3 && ctx.themeIndex <= 6
275
387
  ? !!THEME_TABLE[ctx.themeIndex].light
276
- : !!(ctx && ctx.light);
388
+ : ctx && ctx.themeIndex === AUTO_THEME_INDEX
389
+ ? terminalIsLight()
390
+ : !!(ctx && ctx.light);
277
391
  return light ? DIFF_LIGHT : DIFF;
278
392
  }
279
393
 
@@ -437,7 +551,13 @@ module.exports = {
437
551
  ANSI_LIGHT,
438
552
  THEMES,
439
553
  THEME_TABLE,
554
+ AUTO_THEME_INDEX,
555
+ themeIsLight,
556
+ terminalIsLight,
440
557
  themeForIndex,
558
+ themeContradicts,
559
+ reconcileThemeIndex,
560
+ SIBLING_THEME_INDEX,
441
561
  GLYPH,
442
562
  glyphsFor,
443
563
  VERBS,