aegisone 1.0.22 → 1.0.23

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -2
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -939
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -2
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3020
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -4003
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2179
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -133
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3301
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -227
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3301
  160. package/vendor/desktop/lib/local/entitlement.js +1 -660
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4529
  179. package/vendor/desktop/package.json +3 -2
  180. package/vendor/desktop/preload.js +1 -636
  181. package/vendor/desktop/renderer/app.js +1 -6660
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -736
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2179
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -110
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -133
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -373
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -548
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,881 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Terminal capabilities — ONE probe, resolved once, consulted by everything.
10
- *
11
- * POLICY: aegiscode renders ONE way. `process.platform`, `TERM`, `TERM_PROGRAM`,
12
- * the locale's character set and the Windows terminal markers are all still
13
- * probed — because the support surface reports them — but not one of them may
14
- * move a single byte of what is drawn. PowerShell in Windows Terminal,
15
- * Terminal.app, a legacy Windows console, WSL and zsh over SSH all get the same
16
- * palette, the same mark, the same colour depth, the same control sequences and
17
- * the same `\n`. A screenshot of one is a screenshot of all of them.
18
- *
19
- * What used to differ by platform or environment, and no longer does:
20
- *
21
- * · Windows got the ASCII stencil because `process.platform` was `win32` —
22
- * even *inside Windows Terminal*, which draws █▓▒░▐▛▜▌▝▘ and ✦ exactly like
23
- * zsh does.
24
- * · Terminal.app got a half-stencil (edges stencilled, star narrowed) because
25
- * its font stack lacks ▐▛▜▌▝▘ and renders ✦ through the wide emoji fallback.
26
- * · A non-UTF-8 locale, or `TERM=dumb`, dropped the whole UI to ASCII — so the
27
- * same build looked like a different product in `LANG=C` CI.
28
- * · `TERM=linux|vt100|ansi` and a legacy console flattened truecolor to the 16
29
- * ANSI slots.
30
- * · A redirected run on Windows wrote CRLF; the same run on Linux wrote LF.
31
- *
32
- * The probe is not gone, it is just no longer *implicit*. Every axis below is
33
- * still overridable, and an override is now the ONLY thing that changes the
34
- * rendering. All of them are environment variables and flags, so they are
35
- * spelled and behave identically on every platform, and the resulting look is
36
- * reproducible from a bug report without asking what OS it came from.
37
- *
38
- * The axes:
39
- * glyphs 'unicode' | 'ascii' — the mark's palette (unicode by default)
40
- * face 'native' | 'edges' — the quartile edges ▐▛▜▌▝▘
41
- * star 'native' | 'narrow' — ✦ as a single-cell glyph, or stencilled to `*`
42
- * depth 24 | 8 | 4 | 0 — truecolor by default
43
- * background 'dark' | 'light' — the terminal's OWN background, which is not
44
- * a rendering axis: it selects which of the
45
- * two legible palettes "Auto (match terminal)"
46
- * resolves to. Read from the terminal itself —
47
- * an OSC 11 query at startup (`COLORFGBG`/
48
- * `TERM_BACKGROUND`/`AEGIS_BACKGROUND` win if
49
- * any of them is set, and in a pipe nothing is
50
- * asked at all), never guessed from the
51
- * platform. `backgroundKnown` says whether the
52
- * terminal actually reported it or it is just
53
- * the dark default.
54
- * vt boolean — cursor/erase escapes (on by default)
55
- * cols/rows — the frame, with `AEGIS_WIDTH`/`COLUMNS` over
56
- * the reported size and a stable 80 fallback,
57
- * wideRunes — runes the terminal draws two cells wide
58
- * that the wcwidth table does not know about
59
- * (`AEGIS_WIDE_RUNES=✦`), so every width
60
- * decision stays exact.
61
- *
62
- * Overrides (all read from the environment, all documented in README.md):
63
- * AEGIS_ART=unicode|ascii AEGIS_ASCII=1 AEGIS_UNICODE=0|1
64
- * AEGIS_BACKGROUND=dark|light (also TERM_BACKGROUND, COLORFGBG)
65
- * AEGIS_BACKGROUND_PROBE=0 (never ask the terminal — env signals still read)
66
- * AEGIS_STAR=native|narrow AEGIS_COLOR=0|1|2|3
67
- * AEGIS_VT=0|1 AEGIS_WIDTH=<cols> AEGIS_WIDE_RUNES=<runes>
68
- * AEGIS_FORCE_TRUECOLOR=0 NO_COLOR FORCE_COLOR=0|1|2|3
69
- *
70
- * `caps()` is cached; `setCaps()` re-resolves and notifies subscribers, which is
71
- * how `theme.js` re-materialises its palette and glyph table when the user runs
72
- * `aegiscode --ascii` (the flag is applied before the app is required, so the
73
- * whole session draws with the pass the user asked for) or toggles it in the
74
- * `/terminal` command.
75
- *
76
- * This module requires nothing — no cycles, and it is safe to load first.
77
- */
78
-
79
- // ── the cell-width core ──────────────────────────────────────────────────────
80
- // Real terminal cell width (wcwidth-style), copied verbatim from
81
- // the upstream engine reference. Combining marks and variation selectors occupy
82
- // no cell; CJK fullwidth forms and emoji-presentation glyphs occupy two;
83
- // everything else one. A plain code-point count misaligns every width decision
84
- // the moment a line contains CJK, emoji or a terminal's wide fallback glyph.
85
- const RE_ZERO = /[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u;
86
- const RE_WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u;
87
-
88
- /**
89
- * Windows terminals that can draw the full mark. `WT_SESSION` is set by Windows
90
- * Terminal for every shell it hosts (pwsh, cmd, wsl, git-bash); `TERM_PROGRAM`
91
- * by VS Code and the other Electron/ConPTY hosts; the rest are the classic
92
- * ConPTY-era consoles.
93
- *
94
- * Reported, never consulted: the rendering is uniform whether one of these is
95
- * set or not (see the policy at the top of this file). The list survives so
96
- * `--terminal` can say "Windows VT host (WT_SESSION)" in a bug report, which is
97
- * how a support thread knows the user's console can draw what we draw.
98
- */
99
- const MODERN_WINDOWS = [
100
- 'WT_SESSION',
101
- 'WT_PROFILE_ID',
102
- 'ConEmuANSI',
103
- 'ANSICON',
104
- 'TERM_PROGRAM',
105
- 'WEZTERM_PANE',
106
- 'ALACRITTY_SOCKET',
107
- 'KITTY_WINDOW_ID',
108
- ];
109
-
110
- const TRUTHY_RE = /^(1|true|yes|on)$/i;
111
-
112
- /** Is an env value "on"? (`WT_SESSION=` with no value still counts.) */
113
- function truthy(v) {
114
- if (v == null) return false;
115
- return v === '' || TRUTHY_RE.test(String(v).trim());
116
- }
117
-
118
- /** First defined, non-empty value among `names`. */
119
- function firstEnv(env, names) {
120
- for (const n of names) {
121
- const v = env[n];
122
- if (v != null && v !== '') return { name: n, value: String(v) };
123
- }
124
- return null;
125
- }
126
-
127
- function modernWindows(env) {
128
- return firstEnv(env, MODERN_WINDOWS);
129
- }
130
-
131
- /**
132
- * The locale's character set. POSIX terminals signal UTF-8 support here and
133
- * nowhere else. Recorded for the support surface only: a `LANG=C` shell renders
134
- * the same Unicode mark as a UTF-8 one, so that the same build cannot look like
135
- * a different product on a differently-configured host. A terminal whose font
136
- * genuinely lacks the palette is a deliberate `AEGIS_ART=ascii`.
137
- */
138
- function localeOf(env) {
139
- const hit = firstEnv(env, ['LC_ALL', 'LC_CTYPE', 'LANG']);
140
- return hit ? hit.value : '';
141
- }
142
-
143
- /** The explicit art mode, or 'auto'. */
144
- function artMode(env) {
145
- const raw = String(env.AEGIS_ART || '').trim().toLowerCase();
146
- if (raw === 'ascii' || raw === 'plain' || raw === 'text') return 'ascii';
147
- if (raw === 'unicode' || raw === 'native' || raw === 'utf8' || raw === 'utf-8') return 'unicode';
148
- if (truthy(env.AEGIS_ASCII) || env.AEGIS_UNICODE === '0') return 'ascii';
149
- if (truthy(env.AEGIS_UNICODE)) return 'unicode';
150
- return 'auto';
151
- }
152
-
153
- /**
154
- * What the mark is drawn with — the same answer on every platform.
155
- *
156
- * Only an explicit request moves this: `AEGIS_ART` (the valued switch),
157
- * `AEGIS_ASCII`/`AEGIS_UNICODE` (the booleans it supersedes), or `AEGIS_STAR`
158
- * for a font that renders ✦ through a wide emoji fallback. Everything else —
159
- * `process.platform`, `TERM`, `TERM_PROGRAM`, `WT_SESSION`, the locale's
160
- * character set — is recorded in the resolved `reasons` for the support surface
161
- * and then deliberately ignored.
162
- *
163
- * The old behaviour read those signals and silently downgraded: a `win32`
164
- * process outside a ConPTY host, an Apple Terminal, `TERM=dumb` and any
165
- * non-UTF-8 locale each got a different product. That made the same build look
166
- * unlike itself from one machine to the next, and it made the *reason* for the
167
- * difference invisible to the person looking at the screen. A terminal that
168
- * genuinely cannot draw the palette now says so with the documented override,
169
- * which is a decision the user makes once and the support surface can report.
170
- *
171
- * `platform` is accepted (and reported) but never branched on.
172
- */
173
- function resolveGlyphs(env, platform) {
174
- const starPref = String(env.AEGIS_STAR || '').trim().toLowerCase();
175
- const star = /^(native|wide)$/.test(starPref)
176
- ? 'native'
177
- : /^(narrow|ascii)$/.test(starPref)
178
- ? 'narrow'
179
- : null;
180
- const mode = artMode(env);
181
-
182
- if (mode === 'ascii') {
183
- return { glyphs: 'ascii', face: 'edges', star: 'narrow', reason: 'AEGIS_ART=ascii' };
184
- }
185
- if (mode === 'unicode') {
186
- return { glyphs: 'unicode', face: 'native', star: star || 'native', reason: 'AEGIS_ART=unicode' };
187
- }
188
-
189
- return {
190
- glyphs: 'unicode',
191
- face: 'native',
192
- star: star || 'native',
193
- reason: `uniform default on every platform${star ? ` (AEGIS_STAR=${starPref})` : ''}`,
194
- };
195
- }
196
-
197
- /**
198
- * The terminal's own background brightness: `'dark'` or `'light'`.
199
- *
200
- * This is NOT a rendering axis. Nothing about the mark, the colour *depth*, the
201
- * glyph set or the control sequences moves with it. It exists for one decision
202
- * only — which of the two palettes that are actually legible on the screen in
203
- * front of the user the theme picker's "Auto (match terminal)" row resolves to —
204
- * and getting it wrong is not a subtle difference: the dark palette's primary
205
- * text is `RGB(255,255,255)`, so on a white terminal every word of the product
206
- * is white-on-white. That is a blank screen, not an off-brand one.
207
- *
208
- * `theme.js` used to admit the hole in its own comment ("this client has no
209
- * terminal-background probe and so resolves 'Auto' to the dark palette"), which
210
- * meant the one row whose entire job was to match the terminal could not match
211
- * it, and every user was silently assumed to be on a dark terminal.
212
- *
213
- * The signal, in order — each one written by the terminal about *itself*, so
214
- * none of them is a platform guess:
215
- *
216
- * · `AEGIS_BACKGROUND=dark|light` / `AEGIS_THEME_BACKGROUND` — the explicit
217
- * override, for a terminal that reports nothing (and for a bug report that
218
- * wants the light palette without changing the terminal).
219
- * · `TERM_BACKGROUND=dark|light` — kitty, WezTerm and a few others set it
220
- * directly.
221
- * · `COLORFGBG=fg;bg` — the classic xterm/rxvt report, also emitted by
222
- * Konsole, Mint's GNOME Terminal and the other VTE terminals. Only the LAST
223
- * field (the background's ANSI index) is read. Index 7 is light gray; 11–15
224
- * are the bright half of the table, and a bright background is one white
225
- * text disappears into. 0–6 and 8–10 are dark.
226
- *
227
- * · **the terminal's own answer to an OSC 11 query** — `probeBackground()`
228
- * asks ("what is your background?") and the terminal replies with its real
229
- * colour, which is the one signal that is neither an environment variable
230
- * nor a guess. It exists because the variables above are simply absent on
231
- * the terminals people actually run: Alacritty, for one, sets no
232
- * `COLORFGBG` and no `TERM_BACKGROUND`, so it reported *nothing* and a
233
- * Catppuccin-Mocha Alacritty (`#1e1e2e`) was recorded as "dark" by accident
234
- * — right answer, no evidence. The answer is passed in by the async entry
235
- * point (`probeTerminalBackground()`), never read here, so this function
236
- * stays synchronous, instant and testable.
237
- *
238
- * Anything else — no signal at all, which is every pipe, every CI run and the
239
- * terminals that refuse to answer — resolves to `'dark'` with `known: false`.
240
- * The flag matters: `dark` from a real report is evidence, `dark` from silence
241
- * is a default, and only the caller can decide what to do about the difference.
242
- * A session that reports nothing therefore renders exactly as it did before any
243
- * of this existed.
244
- *
245
- * @param {object} [env] defaults to `process.env`
246
- * @param {{background: 'dark'|'light', reason: string}} [probed] the terminal's
247
- * own OSC 11 answer, when one was obtained (`probeTerminalBackground()`)
248
- * @returns {{background: 'dark'|'light', known: boolean, reason: string}}
249
- */
250
- function resolveBackground(env = process.env, probed = null) {
251
- const override = String(env.AEGIS_BACKGROUND || env.AEGIS_THEME_BACKGROUND || '').trim().toLowerCase();
252
- if (override === 'light') return { background: 'light', known: true, reason: 'AEGIS_BACKGROUND=light' };
253
- if (override === 'dark') return { background: 'dark', known: true, reason: 'AEGIS_BACKGROUND=dark' };
254
-
255
- const declared = String(env.TERM_BACKGROUND || '').trim().toLowerCase();
256
- if (declared === 'light' || declared === 'dark') {
257
- return { background: declared, known: true, reason: `TERM_BACKGROUND=${declared}` };
258
- }
259
-
260
- const fgbg = String(env.COLORFGBG || '').trim();
261
- if (fgbg) {
262
- const parts = fgbg.split(/[;:]/);
263
- const bg = Number(parts[parts.length - 1]);
264
- if (Number.isInteger(bg) && bg >= 0 && bg <= 15) {
265
- const light = bg === 7 || bg >= 11;
266
- return { background: light ? 'light' : 'dark', known: true, reason: `COLORFGBG=${fgbg}` };
267
- }
268
- }
269
-
270
- if (probed && (probed.background === 'light' || probed.background === 'dark')) {
271
- return { background: probed.background, known: true, reason: probed.reason || `osc11 ${probed.background}` };
272
- }
273
-
274
- return { background: 'dark', known: false, reason: 'no terminal background reported (dark default)' };
275
- }
276
-
277
- // ── the terminal's own answer (OSC 11) ───────────────────────────────────────
278
-
279
- /**
280
- * How long to wait for a terminal to answer "what is your background?".
281
- *
282
- * The query is written at startup and abandoned after this, so the deadline is
283
- * a *startup* latency on the terminals that never answer, and nothing else. It
284
- * is spent only when no environment variable already decided the axis — a
285
- * `COLORFGBG`/`TERM_BACKGROUND`/`AEGIS_BACKGROUND` session does not probe at
286
- * all — and every terminal that does answer replies in single-digit
287
- * milliseconds (Alacritty 0.13 answers immediately), so the wait is not the
288
- * common case. 120ms is one frame nobody notices, against a wrong palette the
289
- * user cannot read.
290
- */
291
- const PROBE_TIMEOUT_MS = 120;
292
-
293
- /** The query: `\x1b]11;?\x07` — "report your background", terminated by BEL. */
294
- const OSC11_QUERY = '\x1b]11;?\x07';
295
-
296
- /**
297
- * The answer: `\x1b]11;rgb:1e1e/1e1e/2e2e\x07` (Alacritty, xterm, VTE, kitty),
298
- * terminated by either BEL or ST. Matched loosely and out of a buffer, because
299
- * a reply can arrive split across reads.
300
- */
301
- const OSC11_REPLY = /\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;
302
-
303
- /** A channel of an X11 colour spec: 1–4 hex digits, scaled to 0–255. */
304
- function colorChannel(hex) {
305
- const n = parseInt(hex, 16);
306
- return Math.round((n / (Math.pow(16, hex.length) - 1)) * 255);
307
- }
308
-
309
- /**
310
- * Parse an OSC 11 reply into an RGB triple, or `null` when the text is not one.
311
- *
312
- * Two bodies are accepted, both seen in the wild: X11's `rgb:RRRR/GGGG/BBBB`
313
- * (1–4 hex digits per channel — Alacritty answers `rgb:1e1e/1e1e/2e2e`) and the
314
- * `#rrggbb` shorthand some terminals use instead.
315
- *
316
- * @param {string} text
317
- * @returns {{r: number, g: number, b: number}|null}
318
- */
319
- function parseBackgroundReply(text) {
320
- const m = OSC11_REPLY.exec(String(text == null ? '' : text));
321
- if (!m) return null;
322
- const body = m[1].trim();
323
- const rgb = /^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(body);
324
- if (rgb) return { r: colorChannel(rgb[1]), g: colorChannel(rgb[2]), b: colorChannel(rgb[3]) };
325
- const short = /^#?([0-9a-f]{6})$/i.exec(body);
326
- if (short) {
327
- const h = short[1];
328
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16) };
329
- }
330
- return null;
331
- }
332
-
333
- /** WCAG relative luminance, 0 (black) … 1 (white). */
334
- function relativeLuminance({ r, g, b }) {
335
- const f = (v) => {
336
- const s = v / 255;
337
- return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
338
- };
339
- return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
340
- }
341
-
342
- /**
343
- * The threshold between "a light background" and "a dark one", as relative
344
- * luminance. 0.5 is the midpoint of the perceptual scale and the usual choice;
345
- * a Catppuccin-Mocha `#1e1e2e` scores 0.014 and a #f5f5f5 scores 0.90, so no
346
- * real terminal background sits anywhere near the line — the only colours that
347
- * do are mid-greys, where either palette is legible anyway.
348
- */
349
- const LIGHT_LUMINANCE = 0.5;
350
-
351
- /** `#1e1e2e` — for the `--terminal` report and the startup notice. */
352
- function hexOf({ r, g, b }) {
353
- return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
354
- }
355
-
356
- /**
357
- * Ask the terminal for its own background colour (OSC 11) and answer with RGB.
358
- *
359
- * Written directly, because there is nothing else to read: the environment
360
- * variables in `resolveBackground` are absent on the terminals people run
361
- * (Alacritty sets neither `COLORFGBG` nor `TERM_BACKGROUND`), and the terminal
362
- * will not volunteer its colour — it only answers when asked. This is that ask.
363
- *
364
- * Only ever runs against a real TTY (`stdin` *and* `stdout`), so a pipe, a CI
365
- * run, a test harness and a `--print` invocation never probe and never wait.
366
- * The raw mode it needs is turned back off before returning, and any byte that
367
- * is not the answer — a keystroke that raced the query — is pushed back onto
368
- * `stdin`, so the probe is invisible to the session's own input handling.
369
- *
370
- * @returns {Promise<{background: 'dark'|'light', reason: string, rgb: object}|null>}
371
- * `null` when the terminal did not answer within `timeoutMs`
372
- */
373
- function probeBackground({ stdin = process.stdin, stdout = process.stdout, timeoutMs = PROBE_TIMEOUT_MS, onLeftover = null } = {}) {
374
- return new Promise((resolve) => {
375
- if (!stdin || !stdout || !stdin.isTTY || !stdout.isTTY || typeof stdin.setRawMode !== 'function') {
376
- resolve(null);
377
- return;
378
- }
379
- const wasRaw = !!stdin.isRaw;
380
- let buf = '';
381
- let settled = false;
382
- let timer = null;
383
-
384
- const finish = (value, leftover) => {
385
- if (settled) return;
386
- settled = true;
387
- if (timer) clearTimeout(timer);
388
- // Pause BEFORE dropping the listener. In flowing mode a chunk emitted
389
- // between `removeListener` and `pause` has no subscriber and is silently
390
- // discarded — and that gap is a real window, not a theoretical one: with
391
- // the probe on, 1 run in 10 lost the command typed at launch and hung at
392
- // the fully-drawn welcome screen (9120 bytes, no exit). Pausing first
393
- // stops the flow and leaves any in-flight bytes in the readable buffer,
394
- // where the session pump's `resume()` collects them.
395
- stdin.pause();
396
- stdin.removeListener('data', onData);
397
- try {
398
- if (!wasRaw) stdin.setRawMode(false);
399
- } catch {
400
- /* the terminal closed under us; the read end is already gone */
401
- }
402
- if (leftover) {
403
- // Bytes that were not the answer belong to the session, not to us.
404
- // `onLeftover` routes them back through the caller's key queue, which
405
- // is lossless even when stdin has already ended (see `events.feedKeys`,
406
- // and the 60-second hang its absence caused under `script`/`spawnSync`,
407
- // where the write end closes the moment the command is sent).
408
- if (typeof onLeftover === 'function') {
409
- try {
410
- onLeftover(leftover);
411
- } catch {
412
- /* a broken handback must not cost the probe its answer */
413
- }
414
- } else {
415
- try {
416
- stdin.unshift(Buffer.from(leftover, 'latin1'));
417
- } catch {
418
- /* nothing to push back onto; the deadline was still honoured */
419
- }
420
- }
421
- }
422
- resolve(value);
423
- };
424
-
425
- const onData = (chunk) => {
426
- buf += chunk.toString('latin1');
427
- const rgb = parseBackgroundReply(buf);
428
- if (rgb) {
429
- finish(
430
- { background: relativeLuminance(rgb) > LIGHT_LUMINANCE ? 'light' : 'dark', rgb, reason: `osc11 ${hexOf(rgb)}` },
431
- buf.replace(OSC11_REPLY, ''),
432
- );
433
- } else if (buf.length > 512) {
434
- // Not an answer — most likely a paste or a keystroke arriving before
435
- // the reply. Hand the bytes back rather than eating the user's input.
436
- finish(null, buf);
437
- }
438
- };
439
-
440
- timer = setTimeout(() => finish(null, buf), timeoutMs);
441
- try {
442
- stdin.setRawMode(true);
443
- stdin.resume();
444
- stdin.on('data', onData);
445
- stdout.write(OSC11_QUERY);
446
- } catch {
447
- finish(null, '');
448
- }
449
- });
450
- }
451
-
452
- /**
453
- * Ask the terminal for its background and fold the answer into the live
454
- * capabilities, so every later `caps()`/`themeOf()` sees it.
455
- *
456
- * The single entry point the interactive host calls once at startup, before
457
- * anything is drawn and before the persisted theme is restored: the stored row
458
- * can only be checked against the terminal it is actually drawn on, and the
459
- * restore is what turns that row into the palette of every frame after it.
460
- *
461
- * Deliberately *not* routed through `setCaps()`: that takes a patch over a
462
- * fresh `detect()`, and a detect result carries `cols`/`rows`, which would pin
463
- * the frame to the startup size and make every later resize be ignored. This
464
- * mutates the background axis on the same cached object — so the holders that
465
- * captured it (`theme.js` keeps one) see it, exactly like a `/terminal` change.
466
- *
467
- * @returns {Promise<{background: 'dark'|'light', known: boolean, reason: string}>}
468
- */
469
- async function probeTerminalBackground({ env = process.env, stdin = process.stdin, stdout = process.stdout, platform = process.platform, timeoutMs = PROBE_TIMEOUT_MS, onLeftover = null } = {}) {
470
- const fromEnv = resolveBackground(env);
471
- // An explicit signal is the user's word and outranks the terminal; asking
472
- // anyway would spend the deadline to learn something we would not use.
473
- const probe = fromEnv.known || String(env.AEGIS_BACKGROUND_PROBE || '').trim() === '0' ? null : await probeBackground({ stdin, stdout, timeoutMs, onLeftover });
474
- const bg = resolveBackground(env, probe);
475
- const live = axes();
476
- live.background = bg.background;
477
- live.backgroundKnown = bg.known;
478
- if (live.reasons) live.reasons.background = bg.reason;
479
- for (const fn of listeners) {
480
- try {
481
- fn(live);
482
- } catch {
483
- /* a listener must never break the session's capability resolution */
484
- }
485
- }
486
- return bg;
487
- }
488
-
489
- /**
490
- * Colour depth in bits per channel: 24 truecolor, 8 the 256-colour cube, 4 the
491
- * 16 ANSI slots, 0 no colour at all.
492
- *
493
- * Truecolor, always, unless the user says otherwise. That is the honest default
494
- * for every terminal in use: the 256-colour terminals all pass 24-bit SGR
495
- * through, and a terminal that cannot simply downsamples it itself — which is
496
- * the correct authority for the decision. The old probe tried to guess the
497
- * terminal's ceiling from `TERM`, from the platform and from the Windows console
498
- * markers, and every wrong guess flattened the palette on a machine that could
499
- * have shown it *and* made Windows differ from Linux on identical hardware.
500
- *
501
- * `NO_COLOR` (non-empty), `FORCE_COLOR=0` and `AEGIS_COLOR=0` are the only ways
502
- * to get depth 0; `FORCE_COLOR`/`AEGIS_COLOR` pick 4, 8 or 24; the older
503
- * `AEGIS_FORCE_TRUECOLOR=0` still selects the 256-colour cube.
504
- */
505
- function resolveDepth(env) {
506
- if (env.NO_COLOR != null && env.NO_COLOR !== '') return { depth: 0, reason: 'NO_COLOR' };
507
- const forced = String(env.FORCE_COLOR || '').trim();
508
- if (forced === '0') return { depth: 0, reason: 'FORCE_COLOR=0' };
509
- if (/^[123]$/.test(forced)) {
510
- return { depth: forced === '3' ? 24 : forced === '2' ? 8 : 4, reason: `FORCE_COLOR=${forced}` };
511
- }
512
- const aegis = String(env.AEGIS_COLOR || '').trim();
513
- if (/^[0-3]$/.test(aegis)) {
514
- return { depth: aegis === '0' ? 0 : aegis === '1' ? 4 : aegis === '2' ? 8 : 24, reason: `AEGIS_COLOR=${aegis}` };
515
- }
516
- if (env.AEGIS_FORCE_TRUECOLOR === '0') return { depth: 8, reason: 'AEGIS_FORCE_TRUECOLOR=0' };
517
- return { depth: 24, reason: 'uniform default: truecolor on every platform' };
518
- }
519
-
520
- /**
521
- * Cursor and erase control — on everywhere, since every terminal we ship to
522
- * honours it, and off only for an explicit `AEGIS_VT=0`. The old probe guessed
523
- * from the platform and the console markers, which meant the live spinner line
524
- * behaved differently in a Windows console than in a Linux one; a redirected
525
- * Windows run is no longer treated as a terminal that would print `\x1b[2K` as
526
- * text, because that is the same run everywhere and should render the same.
527
- */
528
- function resolveVt(env) {
529
- const pref = String(env.AEGIS_VT == null ? '' : env.AEGIS_VT).trim();
530
- if (pref === '0') return { vt: false, reason: 'AEGIS_VT=0' };
531
- if (pref === '1' || /^(true|yes|on)$/i.test(pref)) return { vt: true, reason: 'AEGIS_VT=1' };
532
- return { vt: true, reason: 'uniform default: ansi on every platform' };
533
- }
534
-
535
- /**
536
- * The frame. `AEGIS_WIDTH`, then the size the terminal actually reports, then
537
- * `COLUMNS`, then a fixed 80.
538
- *
539
- * The real report outranks `COLUMNS` on purpose: `COLUMNS` is a shell variable
540
- * that bash exports and then *stops updating* on SIGWINCH, so honouring it over
541
- * `stdout.columns` would pin a resized terminal to its old width. A fixed
542
- * fallback rather than a platform guess keeps a redirected run on PowerShell
543
- * byte-identical to the same run in zsh.
544
- */
545
- function resolveSize(env, stdout) {
546
- const forced = parseInt(env.AEGIS_WIDTH || '', 10);
547
- const columns = parseInt(env.COLUMNS || '', 10);
548
- const reported = stdout && Number.isFinite(stdout.columns) && stdout.columns > 0 ? stdout.columns : 0;
549
- const rows = stdout && Number.isFinite(stdout.rows) && stdout.rows > 0 ? stdout.rows : 0;
550
- const wanted = forced > 0 ? forced : reported || (columns > 0 ? columns : 80);
551
- return {
552
- cols: Math.max(20, Math.min(400, wanted)),
553
- rows: Math.max(5, rows || 24),
554
- reason: forced > 0 ? 'AEGIS_WIDTH' : reported ? 'stdout.columns' : columns > 0 ? 'COLUMNS' : 'default 80',
555
- };
556
- }
557
-
558
- /** Runes the terminal draws two cells wide that wcwidth does not know about. */
559
- function resolveWideRunes(env) {
560
- const out = new Map();
561
- for (const ch of String(env.AEGIS_WIDE_RUNES || '')) {
562
- if (ch.trim()) out.set(ch, 2);
563
- }
564
- return out;
565
- }
566
-
567
- /**
568
- * Resolve every axis, purely, from an environment and a stream. Exported so the
569
- * uniformity invariant is a plain function call in a test — no subprocess, no
570
- * TTY.
571
- *
572
- * `platform` is recorded in the result and threaded into the *reasons*, so a
573
- * support paste still says which host it came from; nothing else reads it. The
574
- * line ending is `\n` on every platform, including a redirected run on Windows:
575
- * the one divergence the previous probe allowed is exactly the kind of thing
576
- * that makes two identical invocations produce different bytes.
577
- *
578
- * @param {object} [env] defaults to `process.env`
579
- * @param {object} [stdout] defaults to `process.stdout`
580
- * @param {string} [platform] defaults to `process.platform` (reported, not consulted)
581
- * @param {object} [probed] the terminal's own OSC 11 answer, when the async
582
- * entry point has one (`probeTerminalBackground()`); `null` here means "no
583
- * one asked", which is every synchronous caller — a pipe, a test, `--print`
584
- */
585
- function detect(env = process.env, stdout = process.stdout, platform = process.platform, probed = null) {
586
- const isTTY = !!(stdout && stdout.isTTY);
587
- const glyph = resolveGlyphs(env, platform);
588
- const color = resolveDepth(env);
589
- const vt = resolveVt(env);
590
- const size = resolveSize(env, stdout);
591
- const background = resolveBackground(env, probed);
592
- const host = platform === 'win32' ? modernWindows(env) : null;
593
- return {
594
- platform,
595
- isTTY,
596
- term: String(env.TERM || ''),
597
- termProgram: String(env.TERM_PROGRAM || ''),
598
- locale: localeOf(env),
599
- windowsHost: host ? host.name : '',
600
- glyphs: glyph.glyphs,
601
- face: glyph.face,
602
- star: glyph.star,
603
- depth: color.depth,
604
- color: color.depth > 0,
605
- background: background.background,
606
- // Whether that background was *reported* or merely defaulted. A light/dark
607
- // palette can only be checked against the terminal when this is true: it is
608
- // what stops a stored preference from being overridden on the strength of a
609
- // default that was never evidence.
610
- backgroundKnown: background.known,
611
- vt: vt.vt,
612
- cols: size.cols,
613
- rows: size.rows,
614
- eol: '\n',
615
- wideRunes: resolveWideRunes(env),
616
- reasons: {
617
- glyphs: glyph.reason,
618
- depth: color.reason,
619
- vt: vt.reason,
620
- size: size.reason,
621
- background: background.reason,
622
- },
623
- };
624
- }
625
-
626
- // ── the resolved singleton ───────────────────────────────────────────────────
627
-
628
- let cached = null;
629
- let sizePinned = false;
630
- /**
631
- * The environment `setCaps()` last resolved against. The live size re-read has
632
- * to use THIS, not `process.env`: the CLI entry point builds an environment
633
- * *copy* (`{...process.env, AEGIS_WIDTH}`) so that `--width`/`--ascii` do not
634
- * leak into the session's own child processes. Reading `process.env` in
635
- * `caps()` therefore discarded every override — `aegiscode --width 66` reported
636
- * `80x24 (default 80)` and rendered at 80.
637
- */
638
- let sizeEnv = null;
639
- const listeners = [];
640
-
641
- /**
642
- * The derived axes — glyphs, face, star, depth, vt, wideRunes — resolved once
643
- * per process and re-resolved only by `setCaps()`. The frame is deliberately
644
- * NOT part of this: `process.stdout.columns` changes on SIGWINCH, and the
645
- * window is resized far more often than the palette. Caching the size is how a
646
- * resized terminal ends up pinned to the width it had at module load, which is
647
- * the one bug this split exists to prevent.
648
- */
649
- function axes() {
650
- if (!cached) cached = detect();
651
- return cached;
652
- }
653
-
654
- /**
655
- * The resolved capabilities for this process.
656
- *
657
- * The size is read from the live stream on every call (unless pinned by
658
- * `setCaps({cols,rows})` or `AEGIS_WIDTH`), so a resize is picked up by the
659
- * next frame; everything else comes from the cache. `cols`/`rows` are written
660
- * back onto the same object rather than replaced, so a holder that captured the
661
- * result — `theme.js` keeps one — sees the new frame without re-subscribing.
662
- */
663
- function caps() {
664
- const c = axes();
665
- if (!sizePinned) {
666
- const size = resolveSize(sizeEnv || process.env, process.stdout);
667
- c.cols = size.cols;
668
- c.rows = size.rows;
669
- c.reasons.size = size.reason;
670
- }
671
- // Surfaced so `/terminal` can warn that a pinned frame ignores resizes.
672
- c.pinned = sizePinned;
673
- return c;
674
- }
675
-
676
- /**
677
- * Re-resolve — with `patch` applied on top when given — and tell subscribers.
678
- * `theme.js` subscribes so its palette and glyph table follow a mid-session
679
- * change (`/terminal ascii`), and so does the CLI entry point, which applies
680
- * `--ascii` / `--no-color` before the app module is ever required.
681
- * @param {object} [patch] partial caps, e.g. `{ glyphs: 'ascii', star: 'narrow' }`
682
- * @param {object} [env]
683
- */
684
- function setCaps(patch = null, env = process.env, stdout = process.stdout) {
685
- cached = Object.assign(detect(env, stdout), patch || {});
686
- // Every later frame resolves its size against this same environment, so an
687
- // inherited `AEGIS_WIDTH`/`COLUMNS` override keeps working after a resize
688
- // instead of silently reverting to the stream's own report.
689
- sizeEnv = env || process.env;
690
- // An explicit frame in the patch is a deliberate override, so it must survive
691
- // the live re-read in `caps()`.
692
- sizePinned = !!(patch && (patch.cols != null || patch.rows != null));
693
- // A pinned frame is not re-read from the stream, so the reason the last
694
- // `detect()` recorded (`stdout.columns`) describes where the size came from
695
- // BEFORE the pin — the report would claim the width was the stream's when the
696
- // user had just overridden it with `/terminal width`.
697
- if (patch && patch.cols != null && cached.reasons) cached.reasons.size = 'pinned (override)';
698
- for (const fn of listeners) {
699
- try {
700
- fn(cached);
701
- } catch {
702
- /* a listener must never break the session's capability resolution */
703
- }
704
- }
705
- return cached;
706
- }
707
-
708
- /** Drop the cache so the next `caps()` re-probes (used by tests). */
709
- function resetCaps() {
710
- cached = null;
711
- sizePinned = false;
712
- sizeEnv = null;
713
- }
714
-
715
- /** Subscribe to `setCaps`. Returns an unsubscribe function. */
716
- function onCapsChange(fn) {
717
- listeners.push(fn);
718
- return () => {
719
- const i = listeners.indexOf(fn);
720
- if (i >= 0) listeners.splice(i, 1);
721
- };
722
- }
723
-
724
- // ── width, through the resolved capabilities ─────────────────────────────────
725
-
726
- /** Cell width of one code point, honouring `caps.wideRunes`. */
727
- function cellWidth(ch) {
728
- // `axes()`, not `caps()`: this is called once per code point by `cells()`, on
729
- // every pad and clip in the render path. Re-resolving the frame here would
730
- // parse the environment thousands of times per frame to answer a question
731
- // about fonts, so the hot path reads the cached wide-rune table directly.
732
- const c = axes();
733
- if (c.wideRunes && c.wideRunes.size) {
734
- const o = c.wideRunes.get(ch);
735
- if (o != null) return o;
736
- }
737
- if (RE_ZERO.test(ch)) return 0;
738
- if (RE_WIDE.test(ch)) return 2;
739
- return 1;
740
- }
741
-
742
- /** Display width of a string in terminal cells (ANSI-free input). */
743
- function cells(s) {
744
- let n = 0;
745
- for (const ch of String(s)) n += cellWidth(ch);
746
- return n;
747
- }
748
-
749
- /** Pad a string with spaces to `n` cells (never truncates). */
750
- function padCells(s, n) {
751
- const d = n - cells(s);
752
- return d > 0 ? s + ' '.repeat(d) : s;
753
- }
754
-
755
- // ── colour, through the resolved depth ──────────────────────────────────────
756
-
757
- /** Nearest slot in the xterm-256 cube/greyscale ladder for an RGB triple. */
758
- function rgbTo256(r, g, b) {
759
- if (r === g && g === b) {
760
- if (r < 8) return 16;
761
- if (r > 248) return 231;
762
- return 232 + Math.round(((r - 8) / 247) * 24);
763
- }
764
- const q = (v) => Math.round((v / 255) * 5);
765
- return 16 + 36 * q(r) + 6 * q(g) + q(b);
766
- }
767
-
768
- /** Nearest of the 8 base colours (the bright half is a bold/attribute matter). */
769
- function rgbTo16(r, g, b) {
770
- const named = [
771
- [0, 0, 0, 30],
772
- [205, 0, 0, 31],
773
- [0, 205, 0, 32],
774
- [205, 205, 0, 33],
775
- [0, 0, 238, 34],
776
- [205, 0, 205, 35],
777
- [0, 205, 205, 36],
778
- [229, 229, 229, 37],
779
- ];
780
- let best = named[7];
781
- let bestD = Infinity;
782
- for (const c of named) {
783
- const d = (r - c[0]) ** 2 + (g - c[1]) ** 2 + (b - c[2]) ** 2;
784
- if (d < bestD) {
785
- bestD = d;
786
- best = c;
787
- }
788
- }
789
- return best[3];
790
- }
791
-
792
- /**
793
- * A foreground SGR prefix for the resolved depth: 24-bit, the 256-colour cube,
794
- * the 16 ANSI slots, or nothing at all (`NO_COLOR`, `TERM=dumb`).
795
- *
796
- * Every colour in the UI goes through this — `theme.js` builds its palettes
797
- * from these calls — so a terminal that cannot show truecolor gets a palette it
798
- * *can* show instead of a wall of literal escape text.
799
- */
800
- function rgb(r, g, b) {
801
- const d = caps().depth;
802
- if (d >= 24) return `\x1b[38;2;${r};${g};${b}m`;
803
- if (d >= 8) return `\x1b[38;5;${rgbTo256(r, g, b)}m`;
804
- if (d >= 4) return `\x1b[${rgbTo16(r, g, b)}m`;
805
- return '';
806
- }
807
-
808
- /** A background SGR prefix for the resolved depth (or nothing). */
809
- function bg(r, g, b) {
810
- const d = caps().depth;
811
- if (d >= 24) return `\x1b[48;2;${r};${g};${b}m`;
812
- if (d >= 8) return `\x1b[48;5;${rgbTo256(r, g, b)}m`;
813
- if (d >= 4) return `\x1b[${rgbTo16(r, g, b) + 10}m`;
814
- return '';
815
- }
816
-
817
- // ── reporting (the /terminal command, `aegiscode --terminal`) ────────────────
818
-
819
- /**
820
- * The resolved capabilities as `[label, value]` rows — one shape, same on every
821
- * platform, so a support paste from PowerShell reads like one from zsh.
822
- *
823
- * The first three rows are the host as *reported*: they are the only place the
824
- * platform, the terminal brand and the locale appear, and they cannot influence
825
- * any row below them. That is the point of the layout — a reader can see at a
826
- * glance that the mark, the colour, the control sequences and the line ending
827
- * are the same on every machine, while still knowing which machine produced the
828
- * paste.
829
- */
830
- function describe(c = caps()) {
831
- const host = [c.platform, c.isTTY ? '' : '(no tty)'].filter(Boolean).join(' ');
832
- return [
833
- ['platform', c.windowsHost ? `${host} — ${c.windowsHost}` : host],
834
- ['terminal', c.termProgram || c.term || 'unknown'],
835
- ['locale', c.locale || 'unset'],
836
- // Reported, not obeyed: the background picks the palette "Auto (match
837
- // terminal)" resolves to, and it is the answer to "why is this white on
838
- // white?" — so it belongs in the paste, next to the mark and the colour.
839
- ['background', `${c.background} (${c.reasons.background})`],
840
- ['mark', c.glyphs === 'ascii' ? 'ascii' : c.face === 'edges' ? 'unicode (edges stencilled)' : 'unicode'],
841
- ['star', c.star],
842
- ['color', c.depth === 0 ? 'none' : c.depth >= 24 ? 'truecolor' : c.depth >= 8 ? '256' : '16'],
843
- ['control', c.vt ? 'ansi' : 'plain'],
844
- ['size', `${c.cols}x${c.rows} (${c.reasons.size})`],
845
- ['eol', '\\n'],
846
- ['why', `${c.reasons.glyphs}; ${c.reasons.depth}`],
847
- ];
848
- }
849
-
850
- module.exports = {
851
- detect,
852
- caps,
853
- setCaps,
854
- resetCaps,
855
- onCapsChange,
856
- cellWidth,
857
- cells,
858
- padCells,
859
- rgb,
860
- bg,
861
- rgbTo256,
862
- rgbTo16,
863
- describe,
864
- // internals the tests drive directly
865
- resolveGlyphs,
866
- resolveDepth,
867
- resolveBackground,
868
- resolveVt,
869
- resolveSize,
870
- MODERN_WINDOWS,
871
- // the terminal's own answer (OSC 11): the async startup probe and the pure
872
- // pieces it is built from, so the parse, the threshold and the deadlined read
873
- // are all testable without a real terminal
874
- probeBackground,
875
- probeTerminalBackground,
876
- parseBackgroundReply,
877
- relativeLuminance,
878
- PROBE_TIMEOUT_MS,
879
- LIGHT_LUMINANCE,
880
- OSC11_QUERY,
881
- };
3
+ "use strict";const RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u,MODERN_WINDOWS=["WT_SESSION","WT_PROFILE_ID","ConEmuANSI","ANSICON","TERM_PROGRAM","WEZTERM_PANE","ALACRITTY_SOCKET","KITTY_WINDOW_ID"],TRUTHY_RE=/^(1|true|yes|on)$/i;function truthy(e){return null!=e&&(""===e||TRUTHY_RE.test(String(e).trim()))}function firstEnv(e,n){for(const r of n){const n=e[r];if(null!=n&&""!==n)return{name:r,value:String(n)}}return null}function modernWindows(e){return firstEnv(e,MODERN_WINDOWS)}function localeOf(e){const n=firstEnv(e,["LC_ALL","LC_CTYPE","LANG"]);return n?n.value:""}function artMode(e){const n=String(e.AEGIS_ART||"").trim().toLowerCase();return"ascii"===n||"plain"===n||"text"===n?"ascii":"unicode"===n||"native"===n||"utf8"===n||"utf-8"===n?"unicode":truthy(e.AEGIS_ASCII)||"0"===e.AEGIS_UNICODE?"ascii":truthy(e.AEGIS_UNICODE)?"unicode":"auto"}function resolveGlyphs(e,n){const r=String(e.AEGIS_STAR||"").trim().toLowerCase(),t=/^(native|wide)$/.test(r)?"native":/^(narrow|ascii)$/.test(r)?"narrow":null,o=artMode(e);return"ascii"===o?{glyphs:"ascii",face:"edges",star:"narrow",reason:"AEGIS_ART=ascii"}:"unicode"===o?{glyphs:"unicode",face:"native",star:t||"native",reason:"AEGIS_ART=unicode"}:{glyphs:"unicode",face:"native",star:t||"native",reason:"uniform default on every platform"+(t?` (AEGIS_STAR=${r})`:"")}}function resolveBackground(e=process.env,n=null){const r=String(e.AEGIS_BACKGROUND||e.AEGIS_THEME_BACKGROUND||"").trim().toLowerCase();if("light"===r)return{background:"light",known:!0,reason:"AEGIS_BACKGROUND=light"};if("dark"===r)return{background:"dark",known:!0,reason:"AEGIS_BACKGROUND=dark"};const t=String(e.TERM_BACKGROUND||"").trim().toLowerCase();if("light"===t||"dark"===t)return{background:t,known:!0,reason:`TERM_BACKGROUND=${t}`};const o=String(e.COLORFGBG||"").trim();if(o){const e=o.split(/[;:]/),n=Number(e[e.length-1]);if(Number.isInteger(n)&&n>=0&&n<=15)return{background:7===n||n>=11?"light":"dark",known:!0,reason:`COLORFGBG=${o}`}}return!n||"light"!==n.background&&"dark"!==n.background?{background:"dark",known:!1,reason:"no terminal background reported (dark default)"}:{background:n.background,known:!0,reason:n.reason||`osc11 ${n.background}`}}const PROBE_TIMEOUT_MS=120,OSC11_QUERY="]11;?",OSC11_REPLY=/\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;function colorChannel(e){const n=parseInt(e,16);return Math.round(n/(Math.pow(16,e.length)-1)*255)}function parseBackgroundReply(e){const n=OSC11_REPLY.exec(String(null==e?"":e));if(!n)return null;const r=n[1].trim(),t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(r);if(t)return{r:colorChannel(t[1]),g:colorChannel(t[2]),b:colorChannel(t[3])};const o=/^#?([0-9a-f]{6})$/i.exec(r);if(o){const e=o[1];return{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}return null}function relativeLuminance({r:e,g:n,b:r}){const t=e=>{const n=e/255;return n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)};return.2126*t(e)+.7152*t(n)+.0722*t(r)}const LIGHT_LUMINANCE=.5;function hexOf({r:e,g:n,b:r}){return"#"+[e,n,r].map((e=>e.toString(16).padStart(2,"0"))).join("")}function probeBackground({stdin:e=process.stdin,stdout:n=process.stdout,timeoutMs:r=PROBE_TIMEOUT_MS,onLeftover:t=null}={}){return new Promise((o=>{if(!(e&&n&&e.isTTY&&n.isTTY&&"function"==typeof e.setRawMode))return void o(null);const s=!!e.isRaw;let u="",a=!1,c=null;const i=(n,r)=>{if(!a){a=!0,c&&clearTimeout(c),e.pause(),e.removeListener("data",l);try{s||e.setRawMode(!1)}catch{}if(r)if("function"==typeof t)try{t(r)}catch{}else try{e.unshift(Buffer.from(r,"latin1"))}catch{}o(n)}},l=e=>{u+=e.toString("latin1");const n=parseBackgroundReply(u);n?i({background:relativeLuminance(n)>LIGHT_LUMINANCE?"light":"dark",rgb:n,reason:`osc11 ${hexOf(n)}`},u.replace(OSC11_REPLY,"")):u.length>512&&i(null,u)};c=setTimeout((()=>i(null,u)),r);try{e.setRawMode(!0),e.resume(),e.on("data",l),n.write(OSC11_QUERY)}catch{i(null,"")}}))}async function probeTerminalBackground({env:e=process.env,stdin:n=process.stdin,stdout:r=process.stdout,platform:t=process.platform,timeoutMs:o=PROBE_TIMEOUT_MS,onLeftover:s=null}={}){const u=resolveBackground(e),a=resolveBackground(e,u.known||"0"===String(e.AEGIS_BACKGROUND_PROBE||"").trim()?null:await probeBackground({stdin:n,stdout:r,timeoutMs:o,onLeftover:s})),c=axes();c.background=a.background,c.backgroundKnown=a.known,c.reasons&&(c.reasons.background=a.reason);for(const e of listeners)try{e(c)}catch{}return a}function resolveDepth(e){if(null!=e.NO_COLOR&&""!==e.NO_COLOR)return{depth:0,reason:"NO_COLOR"};const n=String(e.FORCE_COLOR||"").trim();if("0"===n)return{depth:0,reason:"FORCE_COLOR=0"};if(/^[123]$/.test(n))return{depth:"3"===n?24:"2"===n?8:4,reason:`FORCE_COLOR=${n}`};const r=String(e.AEGIS_COLOR||"").trim();return/^[0-3]$/.test(r)?{depth:"0"===r?0:"1"===r?4:"2"===r?8:24,reason:`AEGIS_COLOR=${r}`}:"0"===e.AEGIS_FORCE_TRUECOLOR?{depth:8,reason:"AEGIS_FORCE_TRUECOLOR=0"}:{depth:24,reason:"uniform default: truecolor on every platform"}}function resolveVt(e){const n=String(null==e.AEGIS_VT?"":e.AEGIS_VT).trim();return"0"===n?{vt:!1,reason:"AEGIS_VT=0"}:"1"===n||/^(true|yes|on)$/i.test(n)?{vt:!0,reason:"AEGIS_VT=1"}:{vt:!0,reason:"uniform default: ansi on every platform"}}function resolveSize(e,n){const r=parseInt(e.AEGIS_WIDTH||"",10),t=parseInt(e.COLUMNS||"",10),o=n&&Number.isFinite(n.columns)&&n.columns>0?n.columns:0,s=n&&Number.isFinite(n.rows)&&n.rows>0?n.rows:0,u=r>0?r:o||(t>0?t:80);return{cols:Math.max(20,Math.min(400,u)),rows:Math.max(5,s||24),reason:r>0?"AEGIS_WIDTH":o?"stdout.columns":t>0?"COLUMNS":"default 80"}}function resolveWideRunes(e){const n=new Map;for(const r of String(e.AEGIS_WIDE_RUNES||""))r.trim()&&n.set(r,2);return n}function detect(e=process.env,n=process.stdout,r=process.platform,t=null){const o=!(!n||!n.isTTY),s=resolveGlyphs(e,r),u=resolveDepth(e),a=resolveVt(e),c=resolveSize(e,n),i=resolveBackground(e,t),l="win32"===r?modernWindows(e):null;return{platform:r,isTTY:o,term:String(e.TERM||""),termProgram:String(e.TERM_PROGRAM||""),locale:localeOf(e),windowsHost:l?l.name:"",glyphs:s.glyphs,face:s.face,star:s.star,depth:u.depth,color:u.depth>0,background:i.background,backgroundKnown:i.known,vt:a.vt,cols:c.cols,rows:c.rows,eol:"\n",wideRunes:resolveWideRunes(e),reasons:{glyphs:s.reason,depth:u.reason,vt:a.reason,size:c.reason,background:i.reason}}}let cached=null,sizePinned=!1,sizeEnv=null;const listeners=[];function axes(){return cached||(cached=detect()),cached}function caps(){const e=axes();if(!sizePinned){const n=resolveSize(sizeEnv||process.env,process.stdout);e.cols=n.cols,e.rows=n.rows,e.reasons.size=n.reason}return e.pinned=sizePinned,e}function setCaps(e=null,n=process.env,r=process.stdout){cached=Object.assign(detect(n,r),e||{}),sizeEnv=n||process.env,sizePinned=!(!e||null==e.cols&&null==e.rows),e&&null!=e.cols&&cached.reasons&&(cached.reasons.size="pinned (override)");for(const e of listeners)try{e(cached)}catch{}return cached}function resetCaps(){cached=null,sizePinned=!1,sizeEnv=null}function onCapsChange(e){return listeners.push(e),()=>{const n=listeners.indexOf(e);n>=0&&listeners.splice(n,1)}}function cellWidth(e){const n=axes();if(n.wideRunes&&n.wideRunes.size){const r=n.wideRunes.get(e);if(null!=r)return r}return RE_ZERO.test(e)?0:RE_WIDE.test(e)?2:1}function cells(e){let n=0;for(const r of String(e))n+=cellWidth(r);return n}function padCells(e,n){const r=n-cells(e);return r>0?e+" ".repeat(r):e}function rgbTo256(e,n,r){if(e===n&&n===r)return e<8?16:e>248?231:232+Math.round((e-8)/247*24);const t=e=>Math.round(e/255*5);return 16+36*t(e)+6*t(n)+t(r)}function rgbTo16(e,n,r){const t=[[0,0,0,30],[205,0,0,31],[0,205,0,32],[205,205,0,33],[0,0,238,34],[205,0,205,35],[0,205,205,36],[229,229,229,37]];let o=t[7],s=1/0;for(const u of t){const t=(e-u[0])**2+(n-u[1])**2+(r-u[2])**2;t<s&&(s=t,o=u)}return o[3]}function rgb(e,n,r){const t=caps().depth;return t>=24?`[38;2;${e};${n};${r}m`:t>=8?`[38;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)}m`:""}function bg(e,n,r){const t=caps().depth;return t>=24?`[48;2;${e};${n};${r}m`:t>=8?`[48;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)+10}m`:""}function describe(e=caps()){const n=[e.platform,e.isTTY?"":"(no tty)"].filter(Boolean).join(" ");return[["platform",e.windowsHost?`${n} — ${e.windowsHost}`:n],["terminal",e.termProgram||e.term||"unknown"],["locale",e.locale||"unset"],["background",`${e.background} (${e.reasons.background})`],["mark","ascii"===e.glyphs?"ascii":"edges"===e.face?"unicode (edges stencilled)":"unicode"],["star",e.star],["color",0===e.depth?"none":e.depth>=24?"truecolor":e.depth>=8?"256":"16"],["control",e.vt?"ansi":"plain"],["size",`${e.cols}x${e.rows} (${e.reasons.size})`],["eol","\\n"],["why",`${e.reasons.glyphs}; ${e.reasons.depth}`]]}module.exports={detect:detect,caps:caps,setCaps:setCaps,resetCaps:resetCaps,onCapsChange:onCapsChange,cellWidth:cellWidth,cells:cells,padCells:padCells,rgb:rgb,bg:bg,rgbTo256:rgbTo256,rgbTo16:rgbTo16,describe:describe,resolveGlyphs:resolveGlyphs,resolveDepth:resolveDepth,resolveBackground:resolveBackground,resolveVt:resolveVt,resolveSize:resolveSize,MODERN_WINDOWS:MODERN_WINDOWS,probeBackground:probeBackground,probeTerminalBackground:probeTerminalBackground,parseBackgroundReply:parseBackgroundReply,relativeLuminance:relativeLuminance,PROBE_TIMEOUT_MS:PROBE_TIMEOUT_MS,LIGHT_LUMINANCE:LIGHT_LUMINANCE,OSC11_QUERY:OSC11_QUERY};