aegiscode 6.8.11 → 6.8.13

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/README.md CHANGED
@@ -155,27 +155,60 @@ Only a **legacy** Windows console degrades — and it says why:
155
155
 
156
156
  | host | mark | star | colour | reason |
157
157
  | --- | --- | --- | --- | --- |
158
- | win32 legacy conhost | `ascii` | `narrow` | 16 | Consolas has no block glyphs |
159
- | win32 Windows Terminal | `unicode` | `native` | truecolor | Windows VT host (`WT_SESSION`) |
160
- | Linux/macOS, zsh | `unicode` | `native` | truecolor | — |
161
- | `TERM=dumb` | `ascii` | `narrow` | none | no control sequences |
162
-
163
- The **star defaults to native on Windows VT.** `✦` appears eleven times in the
164
- welcome art, so forcing it narrow there would *create* the divergence this is
165
- meant to remove; ConPTY does font fallback single-width. `AEGIS_STAR=narrow`
166
- is the escape hatch if a host proves otherwise.
158
+ | any host, no override | `unicode` | `native` | truecolor | uniform default: nothing about the host is inferred |
159
+ | win32 legacy conhost | `ascii` | `narrow` | 16 | reported by `--terminal`; set `AEGIS_ART=ascii` to act on it |
160
+ | …requested | `ascii` | `narrow` | 16 | `AEGIS_ART=ascii` / `--ascii` |
161
+
162
+ The rendering is **uniform**: `process.platform`, `TERM`, `TERM_PROGRAM`,
163
+ `WT_SESSION` and the locale's character set are probed and reported
164
+ (`aegiscode --terminal`) but never change a byte that is drawn, because a font
165
+ that lacks a glyph is something only the person looking at the screen can
166
+ settle. Only an explicit switch changes the output, and every switch is spelled
167
+ the same way on every platform.
168
+
169
+ The one thing read from the terminal about *itself* is its background
170
+ brightness, and it is used for one decision only: which of the two legible
171
+ palettes `/theme`'s **Auto (match terminal)** row resolves to. The dark
172
+ palette's body text is white, so on a light terminal the wrong answer is an
173
+ invisible one — and the failure is symmetric: the *light* palette's body text is
174
+ near-black, so restoring it on a dark terminal is invisible too.
175
+
176
+ At startup, on a real terminal, `aegiscode` **asks** — an OSC 11 query
177
+ (`ESC ] 11 ; ? BEL`) that the terminal answers with its own background, e.g.
178
+ `rgb:1e1e/1e1e/2e2e`. That is the only signal that is neither an environment
179
+ variable nor a guess, and it is the one that matters: Alacritty, for instance,
180
+ sets no `COLORFGBG` and no `TERM_BACKGROUND`, so the palette used to be chosen
181
+ from silence. The environment is still read first and wins when set —
182
+ `COLORFGBG` (the background's ANSI index, as xterm, rxvt, Konsole and VTE
183
+ report it), `TERM_BACKGROUND=dark|light` (kitty, WezTerm), or
184
+ `AEGIS_BACKGROUND=dark|light` — and in that case nothing is asked at all. A
185
+ pipe, a CI run and `--print` never probe.
186
+
187
+ What the answer is *for*: a stored `/theme` row that cannot be read on the
188
+ terminal it is being restored on is corrected to the same palette family at the
189
+ other brightness (so "colorblind-friendly" survives, and the light/dark choice
190
+ inside it changes), saved, and announced once. A terminal that reports nothing
191
+ changes nothing — the dark default is not evidence, so a preference is never
192
+ overridden on the strength of it. `/terminal probe` asks again mid-session (for
193
+ a terminal whose theme changed after launch), and `/terminal background
194
+ dark|light` pins it outright without asking. None of this ever moves the mark,
195
+ the colour depth, the control sequences or the line ending.
167
196
 
168
197
  Overrides, at launch — `--ascii`, `--unicode`, `--no-color`, `--color`,
169
198
  `--width <cols>`, `--terminal` (print the report) — and in-session via
170
- `/terminal ascii|unicode|color|no-color|star <native|narrow>|width <cols>|auto|status`.
199
+ `/terminal ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status`.
171
200
  `/terminal auto` re-probes rather than restoring launch flags. `/terminal width`
172
201
  pins the frame, so resizes are ignored until `/terminal auto`; every other
173
- `/terminal` switch leaves resize handling intact.
202
+ `/terminal` switch leaves resize handling intact — the background probe is
203
+ deliberately not routed through the code path that pins a frame, so asking about
204
+ the background can never freeze the width.
174
205
 
175
206
  The same axes are settable by environment for scripts and CI: `AEGIS_ART`,
176
207
  `AEGIS_ASCII`, `AEGIS_UNICODE`, `AEGIS_STAR`, `AEGIS_COLOR`, `AEGIS_VT`,
177
- `AEGIS_WIDTH`, `AEGIS_WIDE_RUNES`. `NO_COLOR` is honoured to the letter —
178
- "present and not an empty string, regardless of its value".
208
+ `AEGIS_WIDTH`, `AEGIS_WIDE_RUNES`, `AEGIS_BACKGROUND` (and `TERM_BACKGROUND`,
209
+ which the terminals that set it write themselves), plus `AEGIS_BACKGROUND_PROBE=0`
210
+ to skip the query while still honouring those variables. `NO_COLOR` is honoured
211
+ to the letter — "present and not an empty string, regardless of its value".
179
212
 
180
213
  ## First run
181
214
 
package/bin/aegiscode.js CHANGED
@@ -50,6 +50,28 @@ Automation:
50
50
  take a base URL but speak no MCP
51
51
  aegiscode mcp help all subcommands and their flags
52
52
 
53
+ Attestation (φ(α) — a sealed record of what a session was):
54
+ aegiscode fingerprint status which authorship key is in use, and where
55
+ aegiscode fingerprint keygen mint a private key (0600, never printed)
56
+ aegiscode fingerprint mint seal the last session as a record
57
+ aegiscode fingerprint verify <file> recompute a record's attestation
58
+ aegiscode fingerprint backup --to DIR copy the key somewhere safe
59
+ aegiscode fingerprint publish [<file>] publish a record, link the copy
60
+ aegiscode fingerprint anchor <file> is the published copy still ours?
61
+ aegiscode fingerprint vault --audit what is in the vault, and is a key in it
62
+ aegiscode fingerprint help all subcommands and their flags
63
+
64
+ Code protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):
65
+ aegiscode gate status can THIS machine edit a gated tree?
66
+ aegiscode gate import-key [PATH] adopt a key dropped at PATH
67
+ (default ~/Downloads/agent.key),
68
+ then delete PATH
69
+ aegiscode gate bind-machine trust this machine in the manifest
70
+ aegiscode gate rotate mint a fresh key, burn the old one
71
+ aegiscode gate add-key add another key (from stdin)
72
+ aegiscode gate lock-status the server-side half of the lock
73
+ aegiscode gate help all subcommands and their flags
74
+
53
75
  Options:
54
76
  -m, --model <id> pin a model id (see /models; default: server choice)
55
77
  --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)
@@ -142,6 +164,28 @@ function parseArgs(argv) {
142
164
  opts.commandArg = sub;
143
165
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
144
166
  argv = [];
167
+ } else if (head === 'fingerprint') {
168
+ // Same position-0 rule and the same reason as `mcp`/`autonomous`: the tail
169
+ // belongs to the subcommand (`--secret-file`, `--code-root`, `--force` are
170
+ // not this parser's flags), so it is handed over verbatim. A bare
171
+ // `fingerprint` is the status report — "is a key configured here?" is the
172
+ // question a user has — not a prompt and not an error.
173
+ const sub = argv[1] && !argv[1].startsWith('-') ? argv[1] : 'status';
174
+ opts.command = 'fingerprint';
175
+ opts.commandArg = sub;
176
+ opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
177
+ argv = [];
178
+ } else if (head === 'gate') {
179
+ // Same position-0 rule and the same reason as `fingerprint`/`mcp`: the
180
+ // tail belongs to the subcommand (`--cwd`, `--paths a b c`, `--keep` are
181
+ // agent-gate.mjs's flags, not this parser's), so it is handed over
182
+ // verbatim. A bare `gate` is the status report — "can this machine edit
183
+ // here?" — not a prompt.
184
+ const sub = argv[1] && !argv[1].startsWith('-') ? argv[1] : 'status';
185
+ opts.command = 'gate';
186
+ opts.commandArg = sub;
187
+ opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
188
+ argv = [];
145
189
  }
146
190
 
147
191
  for (let i = 0; i < argv.length; i++) {
@@ -446,7 +490,7 @@ async function main(argv = process.argv.slice(2)) {
446
490
  const key = rows.reduce((m, [k]) => Math.max(m, k.length), 0);
447
491
  process.stdout.write(`aegiscode ${pkg.version} — terminal capabilities\n\n`);
448
492
  for (const [k, v] of rows) process.stdout.write(` ${k.padEnd(key)} ${v}\n`);
449
- process.stdout.write('\nOverride with --ascii / --color / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_VT, AEGIS_WIDTH (see README).\n');
493
+ process.stdout.write('\nOverride with --ascii / --color / --light / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_BACKGROUND, AEGIS_BACKGROUND_PROBE, AEGIS_VT,\nAEGIS_WIDTH (see README).\n');
450
494
  return 0;
451
495
  }
452
496
 
@@ -458,6 +502,29 @@ async function main(argv = process.argv.slice(2)) {
458
502
  // Account subcommands run before a session is built: they are one-shot,
459
503
  // non-interactive, and must work in a script (`aegiscode login "$KEY"`) as
460
504
  // well as at a prompt.
505
+ // φ(α): the authorship key and the sealed session records. Dispatched here
506
+ // rather than in the account set because its subcommands own their flags —
507
+ // and before a session is built, because `fingerprint mint` must work with no
508
+ // terminal at all (a CI job sealing what it just ran), exactly like the queue.
509
+ if (opts.command === 'fingerprint') {
510
+ const { runFingerprint } = require('../src/fingerprint.js');
511
+ return runFingerprint(opts.commandArg || 'status', opts.commandArgv || [], {
512
+ json: opts.json,
513
+ stdout: process.stdout,
514
+ stderr: process.stderr,
515
+ });
516
+ }
517
+
518
+ // The agent-key gate on aegiscodex-dev / aegiscode-plugin. Dispatched here,
519
+ // before a session is built, for the same reason `fingerprint` is: it is a
520
+ // one-shot administrative question ("can this machine edit that tree?"),
521
+ // not a prompt, and it must work with no terminal at all (a fresh npm
522
+ // install with no git clone is exactly the case this exists for).
523
+ if (opts.command === 'gate') {
524
+ const { runGate } = require('../src/gate.js');
525
+ return runGate(opts.commandArg || 'status', opts.commandArgv || []);
526
+ }
527
+
461
528
  if (ACCOUNT_COMMANDS.has(opts.command)) {
462
529
  return runAccountCommand(opts.command, opts.commandArg, {
463
530
  json: opts.json,
@@ -477,6 +544,22 @@ async function main(argv = process.argv.slice(2)) {
477
544
  // (0 done, 1 a task failed / another drain holds the lock, 2 usage or no
478
545
  // credential) — never the interactive chat path's "no terminal and no prompt".
479
546
  if (opts.command === 'autonomous') {
547
+ // A drain IS the thing the presence panel exists to show: a machine working
548
+ // through a queue with no terminal open. So this path beacons too — with
549
+ // `autonomous: true` and the live pending depth — and it beacons BEFORE the
550
+ // lock is taken, so a drain that exits immediately because another process
551
+ // holds the lock still registers as "this machine is here".
552
+ const presence = require('../src/presence.js');
553
+ const credentials = require('../src/credentials.js');
554
+ presence.start({
555
+ credentials,
556
+ autonomous: true,
557
+ queueDepth: presence.queueDepthReader(),
558
+ });
559
+ // The beacon's timer is unref'd, so nothing here holds the process open;
560
+ // this just cancels a scheduled beat that would otherwise fire mid-teardown.
561
+ process.once('exit', () => presence.stop());
562
+
480
563
  const { runQueueCommand } = require('../src/autonomous.js');
481
564
  return runQueueCommand(opts.commandArg, opts.commandArgv || [], {
482
565
  json: opts.json,
@@ -504,6 +587,31 @@ async function main(argv = process.argv.slice(2)) {
504
587
 
505
588
  const { createApp } = require('../src/app.js');
506
589
 
590
+ // ── presence beacon (aegis1 /api/v1/heartbeat) ───────────────────────────
591
+ //
592
+ // "Who is running aegiscode right now" — the admin panel's presence card.
593
+ // Started for every SESSION, not for the account/lifecycle subcommands above
594
+ // (`login`, `key status`, `--version`, `mcp install` are things a user does
595
+ // once, not a machine being present).
596
+ //
597
+ // Keyed on the credential store's own resolution (env → credentials.json →
598
+ // config.json) so the beacon carries the key this session will actually use,
599
+ // and on the machine fingerprint (client/presence.js) so one laptop is one
600
+ // machine in the panel rather than one row per launch. No key ⇒ presence.js
601
+ // returns an inert store: no timer, no request, no 401 loop.
602
+ //
603
+ // Never fatal: `start()` swallows a load failure and returns an inert store,
604
+ // because a beacon is diagnostic and a session is not.
605
+ const presence = require('../src/presence.js');
606
+ presence.start({
607
+ credentials: require('../src/credentials.js'),
608
+ queueDepth: presence.queueDepthReader(),
609
+ });
610
+ // Every return path below ends the process, and the beacon's timer is
611
+ // unref'd, so this is tidiness rather than a requirement — but it means a
612
+ // quit never races a beat.
613
+ process.once('exit', () => presence.stop());
614
+
507
615
  let prompt = opts.prompt;
508
616
  if (prompt === '-') {
509
617
  if (process.stdin.isTTY) {
@@ -546,7 +654,21 @@ async function main(argv = process.argv.slice(2)) {
546
654
 
547
655
  if (require.main === module) {
548
656
  main()
549
- .then((code) => process.exit(code || 0))
657
+ .then(async (code) => {
658
+ // Before this process exits, let an in-flight presence beat finish. A
659
+ // one-shot run reaches this line in tens of milliseconds, and
660
+ // `process.exit()` would otherwise kill the beacon's first request
661
+ // mid-flight — the machine would run a whole command and still never
662
+ // appear in the admin panel. Bounded (1.5 s) so the beacon can never be
663
+ // the reason a CLI hangs; `flush()` is a no-op when nothing is in flight
664
+ // or when the beacon is off.
665
+ try {
666
+ await require('../src/presence.js').flush();
667
+ } catch {
668
+ /* a beacon must never affect the exit code */
669
+ }
670
+ process.exit(code || 0);
671
+ })
550
672
  .catch((e) => {
551
673
  process.stderr.write(`aegiscode: ${e && e.message ? e.message : e}\n`);
552
674
  process.exit(1);
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.11",
4
+ "version": "6.8.13",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
8
8
  "email": "nborneklint@gmail.com"
9
9
  },
10
- "license": "MIT",
10
+ "license": "AGPL-3.0-or-later",
11
11
  "homepage": "https://aegiscloud.org",
12
12
  "bin": {
13
13
  "aegiscode": "bin/aegiscode.js"
@@ -24,7 +24,7 @@
24
24
 
25
25
  import fs from 'node:fs';
26
26
  import path from 'node:path';
27
- import { fileURLToPath } from 'node:url';
27
+ import { fileURLToPath, pathToFileURL } from 'node:url';
28
28
  import { createRequire } from 'node:module';
29
29
 
30
30
  const require = createRequire(import.meta.url);
@@ -55,6 +55,31 @@ const FILES = [
55
55
  // for the same account on the same machine.
56
56
  'client/auto-provision.js',
57
57
  'client/device-fingerprint.js',
58
+ // The presence beacon (src/presence.js, started by bin/aegiscode.js) — the
59
+ // client half of the aegis1 route /api/v1/heartbeat. presence.js requires
60
+ // presence-constants.js and device-fingerprint.js from the same directory, so
61
+ // the three stay in one vendor tree; a package built without them loses the
62
+ // beacon silently (src/presence.js turns a load failure into an inert store),
63
+ // which is exactly the kind of missing-row bug no error message reports.
64
+ 'client/presence.js',
65
+ 'client/presence-constants.js',
66
+ // φ(α): the authorship key, the sealed session record and the vendored
67
+ // digest module they are built on. src/fingerprint.js resolves all three
68
+ // through resolveClientModule, and they require each other by same-directory
69
+ // relative paths (fingerprint.js -> ./touch.js, attest.js -> ./fingerprint.js
70
+ // and ./authorship-key.js), so all four must land in one vendor tree. A
71
+ // package missing them would fail the fingerprint subcommand at load — loud,
72
+ // but only for the user who tried it.
73
+ 'client/touch.js',
74
+ 'client/fingerprint.js',
75
+ 'client/authorship-key.js',
76
+ 'client/attest.js',
77
+ // The vault: where a sealed record travels so it can be looked at from
78
+ // anywhere, and the module that refuses to send the key with it (a secret in
79
+ // cloud storage can mint records that impersonate the owner). src/fingerprint.js
80
+ // resolves it through resolveClientModule, so a package staged without it
81
+ // loses `fingerprint publish|anchor|vault` at load with MODULE_NOT_FOUND.
82
+ 'client/record-vault.js',
58
83
  // The pooled-brain selection rule: which single entry stands for the Aegis
59
84
  // class. Required at load time by src/models.js (through src/sharedpaths.js),
60
85
  // which the picker, /model and the OpenAI-compatible shim all build their
@@ -164,6 +189,14 @@ const FILES = [
164
189
  // The decode command and the CC0 notice, shipped beside the artifact so a
165
190
  // reader who finds the seal in an installed package can reverse it.
166
191
  'covenant/README.md',
192
+ // The agent-key gate CLI (status/check/init/bind-machine/import-key/rotate/
193
+ // add-key/lock-status). Resolved lazily by src/gate.js through
194
+ // resolveShared() rather than eagerly by deps.js, since it is an ES module
195
+ // (import/export) loaded via dynamic import(), not require(); a package
196
+ // built without it fails only the gate subcommand, at the point someone runs
197
+ // it, not at CLI load. Staged under vendor/tools so a checkout and a
198
+ // published package resolve the same repo-relative path.
199
+ 'tools/agent-gate.mjs',
167
200
  ];
168
201
 
169
202
  function main() {
@@ -285,3 +318,16 @@ function main() {
285
318
  }
286
319
 
287
320
  main();
321
+
322
+ // The gate module is an ES module (import/export), loaded by src/gate.js via
323
+ // dynamic import() rather than require() — so this check is async and runs
324
+ // after main()'s synchronous staging, and a broken staged copy must fail
325
+ // predist here, not wait for the first `aegiscode gate` invocation someone
326
+ // runs after publish.
327
+ const gateStagedPath = path.join(VENDOR, 'tools', 'agent-gate.mjs');
328
+ const gateMod = await import(pathToFileURL(gateStagedPath).href);
329
+ if (typeof gateMod.run !== 'function') {
330
+ console.error('predist: staged tools/agent-gate.mjs exposes no run()');
331
+ process.exit(1);
332
+ }
333
+ console.log('predist: staged tools/agent-gate.mjs loads standalone and exposes run()');
package/src/app.js CHANGED
@@ -23,7 +23,8 @@ const os = require('node:os');
23
23
  const { randomUUID } = require('node:crypto');
24
24
  const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey } = require('./deps.js');
25
25
  const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace } = require('./engine.js');
26
- const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE } = require('./theme.js');
26
+ const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE, AUTO_THEME_INDEX, themeIsLight, reconcileThemeIndex } = require('./theme.js');
27
+ const { probeTerminalBackground } = require('./caps.js');
27
28
  const { LiveRegion, termWidth, w } = require('./screen.js');
28
29
  const { editPreview } = require('./diff.js');
29
30
  const { defaultOpen } = require('./diffview.js');
@@ -38,6 +39,9 @@ const {
38
39
  setMemoryPersist,
39
40
  } = require('./config.js');
40
41
  const credentials = require('./credentials.js');
42
+ // The key pump, so the startup background query can hand back a keystroke that
43
+ // raced its answer (see the `probeTerminalBackground` call in `runInteractive`).
44
+ const events = require('./events.js');
41
45
  const cloudsync = require('./cloudsync.js');
42
46
  const { readSecret } = require('./secret.js');
43
47
  const { normalizeModelCatalog, pickerEntries, catalogIds } = require('./models.js');
@@ -208,13 +212,23 @@ function createApp(options = {}) {
208
212
  // choice is deliberately NOT persisted — a flag that meters every turn must
209
213
  // not survive into a session where nobody asked for it.
210
214
  recallDeep: false,
211
- themeIndex: opts.light ? 2 : 1,
215
+ // "Auto (match terminal)" is the default row, not "Dark mode": the row's
216
+ // whole purpose is that it resolves against the terminal's reported
217
+ // background, and leaving the default on explicit Dark drew the dark
218
+ // palette's white body text over a light terminal — an invisible UI — for
219
+ // every user who never opened the picker.
220
+ themeIndex: opts.light ? 2 : AUTO_THEME_INDEX,
212
221
  vim: false,
213
222
  stream: opts.stream,
214
223
  cwd: process.cwd(),
215
224
  lastRecap: null,
216
225
  sessionId: randomUUID(),
217
226
  };
227
+ // The light flag must start consistent with the default row above, or the
228
+ // ctx and the palette disagree until the first `/theme`: with `AUTO_THEME_INDEX`
229
+ // as the default, a light-background terminal gets the light palette *and*
230
+ // the "light" label, a dark one is byte-identical to before.
231
+ if (commandCtx.themeIndex === AUTO_THEME_INDEX) commandCtx.light = themeIsLight(AUTO_THEME_INDEX);
218
232
  // The transcript rows a handler reads/pushes (user/assistant/note/panel/…).
219
233
  // It is also the source of the engine's conversation history, so /clear and
220
234
  // /new genuinely reset context.
@@ -671,10 +685,7 @@ function createApp(options = {}) {
671
685
  */
672
686
  function emit(lines) {
673
687
  const block = typeof lines === 'string' ? [lines] : lines;
674
- for (const l of block) {
675
- if (capture) capture.push(l);
676
- else out.write(l + '\n');
677
- }
688
+ for (const l of block) out.write(l + '\n');
678
689
  }
679
690
 
680
691
  // --- the ask path ---------------------------------------------------------
@@ -1232,19 +1243,6 @@ function createApp(options = {}) {
1232
1243
  // The one spelling of a provider's settings row, shared with the engine
1233
1244
  // that reads it (`byok:<provider>`) — see engine.js byokNamespace.
1234
1245
  byokNamespace: (p) => byokNamespace(p),
1235
- // Whether a provider key is already on this machine — read through the
1236
- // same `byok:<provider>` rows /byok-key writes, so the model picker's
1237
- // "does this row need a key?" answer cannot disagree with the store that
1238
- // would supply it. Never throws: an injected engine may carry no store.
1239
- hasProviderKey: (p) => {
1240
- const store = engine.settings || null;
1241
- if (!store || !p || typeof store.rawKey !== 'function') return false;
1242
- try { return !!store.rawKey(byokNamespace(p)); } catch { return false; }
1243
- },
1244
- // And whether the ACCOUNT key resolves anywhere (env → credentials.json).
1245
- // A pooled row needs that key, not a provider one, and prompting for a
1246
- // key the machine demonstrably holds is the bug this prevents.
1247
- accountConfigured: () => !!credentials.keyStatus().configured,
1248
1246
  // The class surface: /class switches, /models lists for whichever class
1249
1247
  // is live (the frozen state carries the current one as c.ctx.modelClass).
1250
1248
  listModelsFor: (cls) => listModelsFor(cls),
@@ -1454,20 +1452,9 @@ function createApp(options = {}) {
1454
1452
  async function runOnce(prompt, { json = false } = {}) {
1455
1453
  adoptLegacyKeyOnce();
1456
1454
  if (!client.apiKey) {
1457
- err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}.\n`);
1455
+ err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`);
1458
1456
  return 2;
1459
1457
  }
1460
- // A leading `/` is a LOCAL command at every other entry point (the chatflow
1461
- // dispatches it, the linear REPL dispatches it), so it must be one here too.
1462
- // This path used to skip the dispatcher entirely and hand `"/cost"` to the
1463
- // model as ordinary user text: the request went out as a chat completion, and
1464
- // the pool — which has no answer for a bare slash command — opened an
1465
- // event-stream and sent nothing, so the turn died on the client's 60s idle
1466
- // watchdog with "stream stalled". Every documented non-interactive use of a
1467
- // command (`aegiscode -p "/cost"`, `--json -p "/models"`) was affected, and
1468
- // the failure was indistinguishable from a server outage.
1469
- const parsed = parseLine(prompt);
1470
- if (parsed.kind !== 'prompt') return runOnceCommand(prompt, parsed, { json });
1471
1458
  // Snapshot the account's existing ledger BEFORE the billed call. Without
1472
1459
  // this the refresh after the turn would treat every historical row as new,
1473
1460
  // and the reported charge would be whatever the account spent last rather
@@ -1506,64 +1493,6 @@ function createApp(options = {}) {
1506
1493
  return res.interrupted ? 130 : 0;
1507
1494
  }
1508
1495
 
1509
- /**
1510
- * The one-shot variant of `handleLine`: run a local command and print what it
1511
- * produced. Returns the process exit code.
1512
- *
1513
- * The commands are dispatched through the SAME `handleLine` the interactive
1514
- * loop uses — not a second implementation — so `/cost`, `/models` and friends
1515
- * cannot answer differently depending on whether a human was watching. What
1516
- * this adds over the interactive path is only the two things a non-interactive
1517
- * caller has that the loop does not: an exit code, and, under `--json`, a
1518
- * machine-readable envelope around the command's own output.
1519
- *
1520
- * Preferences are restored first. The interactive entry point calls
1521
- * `restorePrefs()` on startup and this one never did, so a command run through
1522
- * `-p` would have read a context that ignored the config on disk — `/model`
1523
- * with no pin, for instance, would not have seen the model the user pinned.
1524
- */
1525
- async function runOnceCommand(line, parsed, { json }) {
1526
- if (parsed.kind === 'empty') return 0;
1527
- if (parsed.kind === 'unknown') {
1528
- // Straight to stderr, and non-zero: an unknown command is a caller bug, and
1529
- // `-p` is the entry point scripts use. Going through `emit` would put the
1530
- // diagnostic on stdout where a `$(...)` capture would swallow it, and
1531
- // exiting 0 would make a typo look like a success.
1532
- const alt = nearest(parsed.name);
1533
- err.write(`aegiscode: unknown command: /${parsed.name}${alt ? ` — did you mean /${alt}?` : ''}\n`);
1534
- return 2;
1535
- }
1536
- restorePrefs();
1537
- await refreshSpend();
1538
- const lines = json ? [] : null;
1539
- if (lines) capture = lines;
1540
- let keep = true;
1541
- try {
1542
- keep = await handleLine(line);
1543
- } finally {
1544
- capture = null;
1545
- }
1546
- if (json) {
1547
- out.write(
1548
- JSON.stringify(
1549
- {
1550
- command: parsed.kind === 'command' ? '/' + parsed.command.name : line,
1551
- arg: parsed.arg || '',
1552
- // `handleLine` returns false when the command asked to end the
1553
- // session (`/quit`, `/exit`); in one-shot that simply means the
1554
- // command ran and there is nothing further to do.
1555
- ended: keep === false,
1556
- output: lines,
1557
- balance_eur: session.balance,
1558
- },
1559
- null,
1560
- 2
1561
- ) + '\n'
1562
- );
1563
- }
1564
- return 0;
1565
- }
1566
-
1567
1496
  /** Fold one completed turn's usage into the session tallies.
1568
1497
  * @returns {number|null} the total token count for the turn, when known. */
1569
1498
  function recordTurn(res) {
@@ -1876,10 +1805,54 @@ function createApp(options = {}) {
1876
1805
  // appeared to work and every run after it died on startup.
1877
1806
  if (!opts.light && typeof cfg.themeIndex === 'number' && THEME_TABLE[cfg.themeIndex]) {
1878
1807
  commandCtx.themeIndex = cfg.themeIndex;
1879
- commandCtx.light = !!THEME_TABLE[cfg.themeIndex].light;
1808
+ // `themeIsLight` and not `row.light`: row 0's own flag is the dark
1809
+ // fallback, and reading it directly is what pinned a light-terminal user
1810
+ // back to the dark palette on every launch after they chose "Auto".
1811
+ commandCtx.light = themeIsLight(cfg.themeIndex);
1812
+ // A stored row is a preference about a *terminal*, and the terminal it
1813
+ // was chosen on need not be the one it is being restored on. Row 2 is
1814
+ // "Light mode" — primary text `RGB(40,40,40)` — and restoring it onto a
1815
+ // dark terminal drew that text over `#1e1e2e`: contrast 1.11:1, a body of
1816
+ // text present and unreadable. Reading the row as a bare brightness (what
1817
+ // this line did before) is why nothing ever checked. The stored value is
1818
+ // left untouched: the correction belongs to this terminal, and moving
1819
+ // back to a light one restores the choice by itself.
1820
+ const fixed = reconcileThemeIndex(commandCtx.themeIndex);
1821
+ if (fixed.changed) {
1822
+ commandCtx.themeIndex = fixed.index;
1823
+ commandCtx.light = themeIsLight(fixed.index);
1824
+ commandCtx.themeNotice = fixed.reason;
1825
+ // And it is written back. The stored row is a choice that THIS terminal
1826
+ // cannot satisfy, so leaving it on disk would mean the correction is
1827
+ // re-applied — and re-announced — on every launch forever, with the
1828
+ // config asserting a preference the session never honours. `/theme`
1829
+ // still sets it, and the announcement says which value was saved, so
1830
+ // the file and the screen never disagree silently.
1831
+ try {
1832
+ updateConfig({ themeIndex: fixed.index, light: themeIsLight(fixed.index) });
1833
+ } catch {
1834
+ // An unwritable config is not a reason to draw unreadable text: the
1835
+ // in-memory correction above already applies, and the notice says so.
1836
+ commandCtx.themeNotice += ' (could not save it)';
1837
+ }
1838
+ }
1880
1839
  }
1881
1840
  }
1882
1841
 
1842
+ /**
1843
+ * Say the stored theme was corrected for this terminal, once, on a real
1844
+ * screen. Emitted before the session takes the alternate screen so it lands
1845
+ * in scrollback rather than being wiped by the session's first frame, and
1846
+ * only when the correction actually happened — an unasked-for notice about an
1847
+ * unchanged setting is noise.
1848
+ */
1849
+ function themeNoticeFirstRun() {
1850
+ if (!commandCtx.themeNotice) return;
1851
+ const reason = commandCtx.themeNotice;
1852
+ commandCtx.themeNotice = '';
1853
+ emit(render.renderNotice(ctx(), 'warn', `theme: ${reason} (saved)`));
1854
+ }
1855
+
1883
1856
  /**
1884
1857
  * Interactive entry point. On a real terminal this is the full chatflow
1885
1858
  * (alternate screen, header, transcript viewport, spinner, effort line,
@@ -1894,7 +1867,21 @@ function createApp(options = {}) {
1894
1867
  process.stdin.isTTY &&
1895
1868
  process.stdout.isTTY;
1896
1869
  if (tty) {
1870
+ // Ask the terminal what its background is BEFORE the stored theme is
1871
+ // restored, because the restore is a decision *about that background*.
1872
+ // Nothing in the environment answers this on the terminals people run —
1873
+ // Alacritty sets neither `COLORFGBG` nor `TERM_BACKGROUND` — so without
1874
+ // the query the palette was chosen from silence. Bounded (120ms) and
1875
+ // skipped entirely when an env var already decided, so a session that
1876
+ // reports nothing is as fast as it was.
1877
+ //
1878
+ // A keypress can race the terminal's answer into the same read, so any
1879
+ // byte that was not the answer is handed back to the key pump's own queue
1880
+ // rather than to the stream: `events.feedKeys` delivers it exactly as a
1881
+ // `data` event would have, including after stdin has ended.
1882
+ await probeTerminalBackground({ onLeftover: (text) => events.feedKeys(text) });
1897
1883
  restorePrefs();
1884
+ themeNoticeFirstRun();
1898
1885
  adoptLegacyKeyOnce();
1899
1886
  // Give aegis1 a chance to auto-provision a free device key BEFORE
1900
1887
  // deciding whether onboarding needs to ask for one — a fresh install